Back to paper library
Paper notesarXiv 2022ACM Multimedia 2022

DiT

A Different Dictionary

Original paper

DiT: Self-supervised Pre-training for Document Image Transformer

Paper authors

Junlong Li · Yiheng Xu · Tengchao Lv · Lei Cui · Cha Zhang · Furu Wei

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

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

@misc{documentunderstandingdit2022,
  title = {{DiT: Self-supervised Pre-training for Document Image Transformer}},
  author = {Junlong Li and Yiheng Xu and Tengchao Lv and Lei Cui and Cha Zhang and Furu Wei},
  year = {2022},
  eprint = {2203.02378},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2203.02378}
}
On this page

Train a document layout detector, and the backbone is usually a ResNet trained on ImageNet. It knows cats, dogs, and bicycles, but it has never seen a form.

Everyone knows this. The PubLayNet paper ran an experiment on it: detecting tables and paragraphs on insurance documents, a model initialized from PubLayNet did better than one initialized from ImageNet. But PubLayNet was labeled automatically from PubMed papers and contains nothing but academic paper layouts; DocBank and TableBank are the same, sourced from arXiv or from Word and LaTeX documents. Real-world invoices, receipts, reports, and handwritten letters are missing from all of these datasets.

What the document field lacked was an ImageNet of its own, large, diverse, and human-annotated. It never showed up.

The Microsoft Research Asia team behind the LayoutLM series tried a different angle. Annotations were unaffordable, but unannotated document images were plentiful; IIT-CDIP alone has 42 million scanned pages. On the vision side, a ready-made method happened to exist too. BEiT had shown that a ViT, like BERT, could be pretrained self-supervised by “masking part of the input and guessing it back.”

Connect the two, and you get this paper's DiT (Document Image Transformer). While connecting them, though, the authors found one component that couldn't be carried over as is.

Defining the Problem

What the authors call “vision-based Document AI” covers the tasks that look only at the image and don't rely on OCR text:

  • Document classification: decide whether a scan is a letter, a form, an invoice, or a résumé.
  • Layout analysis: box the titles, paragraphs, lists, tables, and figures.
  • Table detection: find where the tables are on a page.
  • Text detection: find the box of every word for OCR.

The standard approach for these tasks at the time was a CNN backbone with supervised pretraining on ImageNet or COCO, fine-tuned on task data. The multimodal models of the LayoutLM series were no different; their image branch relied on these CNNs to extract features. The authors point out that these vision models lose accuracy as soon as they meet real documents whose layouts differ from the training data, and the resulting errors propagate to the models downstream.

Self-supervised pretraining on documents with BEiT's recipe sounds straightforward. The problem lies in where BEiT's “answers” come from.

BEiT doesn't predict pixels; it predicts discrete visual tokens. The job of turning an image into tokens falls to DALL-E's dVAE, trained on 400 million natural images, which learned to describe a small patch of image with one of 8,192 IDs. The entries in this “dictionary” are textures of sky, fur, leaves, and faces. Is it the right tool for describing a page crammed with small print and table lines?

Solving the Problem

First, Switch Dictionaries

Diagram of DiT's pretraining. The top half is step one: 42 million document images from IIT-CDIP go into the dVAE encoder (three stride-2 convs, 8× downsampling), map to a codebook of 8,192 visual tokens, and a decoder draws the IDs back as images; the loss is MSE reconstruction error plus perplexity. The bottom half is step two: a 224×224 document page is cut into 14×14 patches, several contiguous blocks of which are masked in gray; the masked page goes into the DiT encoder (ViT-B, 12 layers, 768-d), which outputs 8,192-class probabilities at each masked position; the same page at 112×112 goes into the frozen dVAE encoder to produce 14×14 token IDs, and only the IDs at masked spots serve as targets, with a cross-entropy (CE) loss computed between the two.
Drawn for this note from Sections 3.2 and 4.2 of the paper; mask positions are illustrative.

The authors' answer is no, so the first step is to switch to a different dictionary.

They adapted an open-source DALL-E implementation and retrained a dVAE on the 42 million document page images of IIT-CDIP. The specs match DALL-E's: a codebook of 8,192 IDs, and an encoder with three layers, each a stride-2 convolution plus a ResNet block, for 8× downsampling overall. Training uses two losses, an MSE loss for reconstructing the image and a perplexity loss that encourages the model to use all the IDs in the codebook, so that most cells don't crowd onto a handful of IDs. The input is 224×224, the learning rate 5e-4, the temperature annealed to a minimum of 1e-10, and training runs for 3 epochs over all of IIT-CDIP.

The 8× downsampling is the crucial number. Feed in a 112×112 image, and out come exactly 14×14 IDs, matching one-to-one the 14×14 patches you get when DiT's 224×224 input is cut into 16×16 patches.

Does switching dictionaries actually make a difference? The paper includes a set of reconstructions: one page each from PubLayNet and ICDAR 2019 cTDaR, encoded with each dictionary and drawn back. In the pages drawn with DALL-E's dictionary, the boundaries of text lines and characters blur together; those drawn by the document dVAE are closer to the original, with clear edges. This is the only evidence in the whole paper that compares the two tokenizers directly, and it is qualitative. We'll come back to this in the Discussion.

Mask 40%, Guess the IDs

Once the dictionary is ready, pretraining is BEiT's recipe.

DiT's architecture is simply ViT. A document page is resized to 224×224 and cut into 16×16 patches, giving 14×14 = 196 of them. Each patch goes through a linear projection, gets a 1D position embedding added, and enters the Transformer. DiT-B, like ViT-Base, has 12 layers, 768 dimensions, and 12 attention heads; DiT-L has 24 layers, 1,024 dimensions, and 16 heads, about 300 million parameters.

Work out the resolution first. Shrink an A4 scan to 224×224, and its 21 cm width becomes 224 pixels, so each patch covers a strip about 1.5 cm wide. Body text is typically about 3 mm tall, and A4's 29.7 cm height is squeezed into 224 pixels as well, leaving characters just two or three pixels tall; you can make out lines of text but not the characters themselves. What DiT learns is closer to layout-level appearance, like “this block is a paragraph, that block is a table, there's a horizontal line here.”

During pretraining, the authors use BEiT's blockwise masking, which masks a whole block of adjacent patches at a time, about 40% in total. Masked patches are replaced with a learnable [MASK] embedding, and the whole sequence goes into DiT. On the other side, the same page is resized to 112×112 and fed to the frozen document dVAE, yielding 14×14 IDs. At each masked position, DiT outputs a probability distribution over 8,192 classes, and cross-entropy is computed against the ID at that position. Unmasked positions don't count toward the loss.

Written as a formula, it is BEiT's MIM objective:

LMIM=−∑i∈Mlog⁡p(zi∣xM)\mathcal{L}_{\text{MIM}} = -\sum_{i \in \mathcal{M}} \log p\left(z_i \mid x^{\mathcal{M}}\right)

M\mathcal{M} is the set of masked positions, ziz_i is the dVAE ID of cell ii, and xMx^{\mathcal{M}} is the input after masking.

Guessing IDs instead of pixels is BEiT's core idea. Much of the detail in a patch's pixel values is noise, such as scan grain or paper tint; an ID first classifies the patch as one of 8,192 kinds of appearance. The model has to guess “roughly what this spot looks like,” without restoring every gray value. With the document dVAE, these 8,192 appearances describe document elements such as text lines, table lines, blank space, and stamps.

The remaining pretraining settings are 500K steps, batch size 2,048, learning rate 1e-3, 10K warmup steps, weight decay 0.05, and stochastic depth 0.1; dropout is turned off, which, like the mask ratio, follows BEiT. Multi-page documents are split into single pages, and random resized crop is applied during training.

From One Scale to Four

A pretrained DiT is just a backbone; to use it for downstream tasks, it still needs heads attached.

Document classification is the simplest. Average the outputs of the 196 patches and attach a linear classifier.

Detection is a bit more involved. For layout analysis, table detection, and text detection, the authors use Mask R-CNN or Cascade R-CNN from Detectron2, detectors that expect multi-scale feature maps from an FPN. ViT has a single resolution from start to finish; every layer is a token grid of the same size.

Diagram of turning ViT's single scale into FPN's four scales. On the left, an 800×800 document image is cut into 16×16 patches, giving 50×50 tokens, which enter layers 1 through 12, stacked from bottom to top. The output of layer 4 goes through two 2×2 transposed convs and is upsampled 4× to 200×200 (stride 4); layer 6 goes through one 2×2 transposed conv and is upsampled 2× to 100×100 (stride 8); layer 8 gets no change and stays 50×50 (stride 16); layer 12 goes through 2×2 max pooling and is downsampled 2× to 25×25 (stride 32). All four scales go into the FPN, which feeds Mask R-CNN or Cascade R-CNN.
Drawn for this note from Section 3.3 of the paper; feature-map sizes are computed for an 800×800 input.

The authors take one layer from each of four different depths and resize each one separately. With dd layers in total:

  • Layer d/3d/3: two stride-2 2×2 transposed convolutions, upsampling 4×.
  • Layer d/2d/2: one transposed convolution, upsampling 2×.
  • Layer 2d/32d/3: left unchanged.
  • Layer dd: 2×2 max pooling, downsampling 2×.

DiT-B has 12 layers, so these are layers 4, 6, 8, and 12. Input images are much larger for detection. Take 800×800: with a patch size of 16, every ViT layer is a 50×50 grid, which works out to stride 16. After the processing above, the four layers become 200×200, 100×100, 50×50, and 25×25, the familiar FPN strides of 4, 8, 16, and 32. DiT didn't invent this; the authors borrowed it from contemporary work on attaching ViTs to detectors.

Discussion

Experimental Setup

Each of the four downstream tasks uses one public dataset:

  • RVL-CDIP: 400,000 grayscale document images in 16 classes, 25,000 per class; the metric is classification accuracy.
  • PubLayNet: layout analysis with five classes; the metric is mAP@[0.50:0.95], reported on the validation set.
  • ICDAR 2019 cTDaR: table detection, split into two subsets, archival (600 training and 199 test images: hand-drawn accounting books, stock tables, train timetables, production census tables) and modern (600 training and 240 test images: journals, forms, financial reports, in both Chinese and English). The metric is weighted F1, which averages the F1 at IoU thresholds of 0.6, 0.7, 0.8, and 0.9, weighted by the threshold value, so stricter thresholds weigh more.
  • FUNSD: only the first task, word-level text detection, scored by F1 at [email protected].

There are two kinds of baselines. One is a CNN, ResNeXt-101-32×8d; the other is image Transformers of the same size, DeiT-B, BEiT-B, and MAE-B, all three pretrained only on ImageNet-1K. The authors reran the fine-tuning of every baseline themselves, and the parameter counts are close to DiT-B's.

All Together First

Gains of each backbone over ResNeXt-101 on four tasks, in percentage points. RVL-CDIP classification (ResNeXt-101 at 90.65): BEiT-B +0.44, MAE-B +0.77, DiT-B +1.46, DiT-L +2.04. PubLayNet layout analysis (ResNeXt-101 at 92.0): BEiT-B +1.1, MAE-B +1.0, DiT-B +1.5, DiT-L +2.1. cTDaR table detection (ResNeXt-101 at 94.46): BEiT-B +0.57, MAE-B +0.20, DiT-B +0.84, DiT-L +1.39. FUNSD text detection (ResNeXt-101 at 93.07): BEiT-B +0.30, MAE-B +0.74, DiT-B +0.81, DiT-L +0.86.
Drawn for this note from the numbers in Tables 1–4 of the paper; detection tasks show Mask R-CNN results.

This figure boils four results tables down to one thing, how many points each backbone gains over ResNeXt-101. In every group, the blue DiT-B bar is longer than the gray BEiT-B bar, and the orange DiT-L bar is longer still.

How much longer depends on the task. BEiT-B and DiT-B have identical architectures; the only differences are the pretraining data and the dictionary. The two bars differ by 1.02 points on RVL-CDIP, by just 0.4 on PubLayNet, and by 0.5 on FUNSD text detection (F1 0.9337 vs. 0.9388). Document-specific pretraining helps most clearly on classification, and the advantage narrows on detection tasks.

Document Classification

ModelTypeParamsAccuracy (%)
Afzal et al. (2017)Single–90.97
Das et al. (2018)Single–91.11
Sarkhel & Nandi (2019)Ensemble–92.77
ResNeXt-101-32×8dSingle88M90.65
DeiT-BSingle87M90.32
BEiT-BSingle87M91.09
MAE-BSingle87M91.42
DiT-BSingle87M92.11
DiT-LSingle304M92.69

Compiled from Table 1 of the paper. All models use images only, with 224×224 input.

DiT-B beats the previous best single model, 91.11, by 1 point, and DiT-L's 92.69 is already close to the previous best ensemble, 92.77.

Every number in this table uses images only. On the same RVL-CDIP, LayoutLM, using OCR text and coordinates plus image features, scores 94.42; LayoutLMv2-large scores 95.64. On this task DiT can't yet beat models that read the text; its role is to serve as the image backbone for those models.

Layout Analysis

On the PubLayNet validation set, Mask R-CNN with DiT-B reaches an overall mAP of 0.935, and with DiT-L 0.941; with the same detector, ResNeXt-101 gets 0.920, and the three ViTs pretrained on ImageNet (DeiT-B, BEiT-B, MAE-B) all fall between 0.930 and 0.932. The Mask R-CNN from the original PubLayNet paper is listed at 0.910 in this table.

The authors say the gains come mainly from two classes, lists and figures. Lists rise from 0.918–0.924 to 0.929 (DiT-B) and 0.945 (DiT-L), and figures from 0.952–0.959 to 0.967 and 0.968. On titles, DiT-B's 0.871 is actually lower than DeiT-B's 0.874.

With Cascade R-CNN, DiT-B reaches 0.945 and DiT-L 0.949, 1.0 and 1.4 points higher than ResNeXt-101 with Cascade (0.935).

Table Detection

cTDaR's two subsets differ a lot. Archival consists of old accounting books and timetables, with handwriting and tinted backgrounds; modern consists of contemporary PDFs.

The authors first found that fine-tuning DiT directly on the raw archival images worked poorly. Their fix was to apply adaptive binarization with OpenCV first, suppressing background tint and stains before handing the images to the model. Fine-tuning also uses multi-scale training, following DETR.

On the two subsets combined, Mask R-CNN with DiT-L reaches a weighted F1 of 95.85, against 94.23 for the competition winner; with Cascade R-CNN, DiT-L gets to 96.55. At the strictest IoU threshold, 0.9, DiT-B scores 93.36, BEiT-B 92.44, and ResNeXt 91.36, so its boxes are also placed more precisely.

The archival subset is an exception. Here BEiT-B's 96.35 is higher than DiT-B's 96.24. The authors' explanation is that DALL-E's dVAE was trained on 400 million color images, while DiT's dictionary has only seen grayscale documents and may fall short on colored historical documents. This is the authors' speculation; the paper runs no experiment to verify it. Still, it happens to show that switching dictionaries comes at a cost.

Text Detection

ModelPrecisionRecallF1
Faster R-CNN (FUNSD paper)0.7040.8480.76
DBNet0.87640.84000.8578
Commercial OCR engine0.87620.82600.8504
ResNeXt-101-32×8d0.93870.92290.9307
BEiT-B0.94120.92630.9337
MAE-B0.94410.93210.9381
DiT-B0.94700.93070.9388
DiT-L0.94520.93360.9393
DiT-L (+ synthetic data)0.95430.93170.9429

Compiled from Table 4 of the paper; FUNSD text detection, [email protected]. ResNeXt through DiT all use Mask R-CNN.

The biggest gap in this table isn't between DiT and the other backbones but between DBNet and Mask R-CNN. A fine-tuned DBNet and a commercial OCR engine both sit around 0.85; switch to Mask R-CNN, with any backbone, and the score jumps above 0.93. The backbones range from 0.9307 to 0.9393, all packed within 0.01.

The last row is the result of training first on 1 million synthetic documents and then fine-tuning on FUNSD, reaching an F1 of 0.9429. The paper doesn't explain how the synthetic data was generated.

Two Variables Never Separated

Between DiT and BEiT-B, two things actually changed. The pretraining images went from ImageNet to IIT-CDIP, and the dictionary went from DALL-E's to the document dVAE. The paper doesn't run the control of “pretraining on IIT-CDIP but with the DALL-E dictionary,” so for the score gaps above, there's currently no way to tell how much comes from the document images and how much from the new dictionary.

The only window onto the dictionary's contribution is that set of reconstructions, and all it shows is sharper reconstruction. Between sharper reconstruction and better pretrained representations there is still one more step, and the paper doesn't measure it.

And yet “switching dictionaries” is the main difference between this paper and BEiT.

What Was Released

In the dit directory of the unilm repo, the authors released fine-tuning code for classification, layout analysis, table detection, and text detection, along with pretrained weights for DiT-B and DiT-L and fine-tuned weights for each task, which are also on Hugging Face. The dit directory carries no license of its own and so falls under the MIT license of the unilm repo as a whole; in the same repo, the READMEs for LayoutLMv2 and LayoutLMv3 each specify the non-commercial CC BY-NC-SA.

Neither the pretraining code nor the document dVAE was made public. In June 2022, someone asked on GitHub whether the dVAE or its training code could be provided so they could pretrain DiT themselves. The maintainer replied, “Currently, we do not have plans to release the code for pre-training” (issue #745), and nothing more came of it.

The dictionary the paper spends the most pages explaining is the one component that was never handed over.

Conclusion

What DiT does is straightforward. It takes BEiT's masked image modeling and pretrains a ViT on 42 million unannotated scanned document pages, and its only change is to retrain the dVAE on the same documents first, so that the “answers” are written in a document dictionary. It beats the ImageNet backbones of its time on all four vision-based tasks, outperforming BEiT-B by 1 point on document classification, while on detection tasks the gap narrows to a few tenths.

It also leaves the question it most wants to stress unanswered. The paper never measures how many points the new dictionary is actually worth, and on colored historical documents, the old dictionary even wins by a little.

Still, the dictionary wasn't built for nothing. A little over a month later, LayoutLMv3 also handed its image-side MIM targets to a tokenizer, and the one it used was initialized from DiT's tokenizer. Outsiders, however, never got their hands on this dictionary, so most people trying to redo LayoutLMv3's pretraining have had to make do with DALL-E's.

If you want to replace an ImageNet backbone for your own documents, DiT's weights are under the MIT license and ready to fine-tune; if you want its dictionary, you'll have to train one yourself.