Back to paper library
Paper notesarXiv 2022ICML 2023

Pix2Struct

Ctrl + U

Original paper

Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding

Paper authors

Kenton Lee · Mandar Joshi · Iulia Turc …

Show all 10 authors

Kenton Lee · Mandar Joshi · Iulia Turc · Hexiang Hu · Fangyu Liu · Julian Eisenschlos · Urvashi Khandelwal · Peter Shaw · Ming-Wei Chang · Kristina Toutanova

Publication
ICML 2023Conference
First submitted to arXiv
arXiv:2210.03347
Cite this paper · BibTeX

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

@misc{documentunderstandingpix2struct2022,
  title = {{Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding}},
  author = {Kenton Lee and Mandar Joshi and Iulia Turc and Hexiang Hu and Fangyu Liu and Julian Eisenschlos and Urvashi Khandelwal and Peter Shaw and Ming-Wei Chang and Kristina Toutanova},
  year = {2022},
  eprint = {2210.03347},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2210.03347}
}
On this page

Press Ctrl + U in a browser, and the HTML behind the page in front of you is laid bare. Which node holds the heading, what a button says, and what an image's alt text is are all spelled out plainly.

Pix2Struct's pretraining task is this action in reverse. No source code, just a screenshot of a web page, and the model has to write out the HTML itself.

The paper comes from Google Research, with Kenton Lee and Mandar Joshi as co-first authors. Three people on the author list were also BERT authors: Kenton Lee, Ming-Wei Chang, and Kristina Toutanova. What they wanted was a general model that looks at an image and writes text, with one set of weights that works for reading charts, phone screens, and scanned documents alike.

Defining the Problem

What documents, charts, infographics, and mobile app screens have in common is that text and graphics are stuck together. A bar chart's numbers are written on the bars, a button's function depends on its icon and the words beside it, and a form's field names and filled-in values correspond by position. The authors call this kind of thing visually-situated language, roughly “language that lives inside the picture.”

At the time, each domain had its own approach, and all of them depended on external tools:

  • Documents: run OCR first, then hand the text, coordinates, and image to a model like LayoutLMv3.
  • Mobile UIs: get the Android view hierarchy, the component tree behind the app.
  • Charts and diagrams: first use tools to convert charts back into tables, or detect components such as arrows and boxes.

Each pipeline works only in its own domain, and data, architectures, and training objectives can't be shared.

Some had already taken the OCR-free route. Donut, also covered in this batch of notes, has the model look directly at document images and, during pretraining, read out the text on the page in order. The authors consider this an important step, but a pretraining task that only asks the model to read out surface text limits what it can learn from large amounts of unlabeled data.

There's another problem fewer people worry about, the shape of the image. A standard ViT first resizes the image to a fixed square, then cuts it into 16 × 16 patches. Squash a tall, narrow phone screenshot or an infographic several thousand pixels long into a square, and the text gets flattened or stretched.

Solving the Problem

Pixels In, Text Out

Original Figure 1: four input images on the top row, with the corresponding output text on the bottom row. Leftmost is an example of screenshot parsing pretraining, a pricing-plan web page where the Pro plan's $15 and some of the text are masked by red crosses, with the parse written in nested brackets below, <<Pro> <<<$15> </mo>> <<20 users included> <10 GB of storage> <Priority email support> <Help center access>> <Get started>>>; next is a food web diagram from AI2D, with the question written above the diagram and the answer carnivore; then a Screen2Words screen from a weather video app, with the output list of videos for weather reports in different locations; rightmost is a DocVQA roster document with the question Who is the High Chancellor? written at the top and the answer Fred LeCrone.
Original Figure 1, Lee et al., from PDF page 2, CC BY 4.0.

Start with the figure's format. The four on the top row are all images and the four on the bottom are all text, and the model's job is always “look at the top, write the bottom.” The leftmost is pretraining; the other three are downstream tasks. Notice that for AI2D and DocVQA, the question isn't fed to the model separately but printed directly at the top of the image.

The architecture itself is standard, a ViT image encoder feeding a Transformer text decoder. Base has 12 encoder layers, 12 decoder layers, and a hidden size of 768, about 282 million parameters; Large has 18 layers and a hidden size of 1536, about 1.3 billion parameters. The authors' own analogy is that they wanted a visual T5, with inputs and outputs kept as simple as possible and all the differences between tasks packed into data preprocessing.

So this paper's contribution isn't the architecture. It lies in how the input is cut up, what pretraining teaches, and how downstream tasks are squeezed into one format.

No Squashing

Original Figure 2: the left half is the paper's variable-resolution input, a portrait-format infographic about small businesses in Western Australia, resized with its aspect ratio preserved and cut into patches along red grid lines, still in portrait format; the right half is a standard ViT's fixed-resolution input, where the same image is resized to nearly square and the text and pie chart are squashed before being cut into patches. Both sides use 36 patches as the example.
Original Figure 2, Lee et al., from PDF page 3, CC BY 4.0.

The right half shows the standard ViT approach, where a portrait infographic is forced into a square and the “78%” is visibly stretched sideways. The left half shows Pix2Struct's approach, which first decides the maximum number of patches the image may use and then scales it proportionally so that the number of patches cut out stays just within that limit.

In the official code and the Hugging Face port, the computation goes like this. With patch size p=16p = 16, a limit of NN patches, and an original image of height HH and width WW:

s=N⋅pH⋅pWrows=⌊sHp⌋,cols=⌊sWp⌋\begin{aligned} s &= \sqrt{N \cdot \frac{p}{H} \cdot \frac{p}{W}} \\ \text{rows} &= \left\lfloor \frac{sH}{p} \right\rfloor, \quad \text{cols} = \left\lfloor \frac{sW}{p} \right\rfloor \end{aligned}

The image is resized to rows⋅p\text{rows} \cdot p high and cols⋅p\text{cols} \cdot p wide, then cut into patches, with blank padding patches filling any shortfall below NN.

Let's run the numbers on a scanned document page. Suppose the image is 1700 pixels wide and 2200 pixels tall, and the Base model's limit when fine-tuning on DocVQA is 4096 patches. Plugging in gives s≈0.53s \approx 0.53, which yields 72 rows and 56 columns, 4,032 patches in all, and the image is resized to 1152 × 896. The aspect ratio goes from 2200 : 1700 to 1152 : 896, almost unchanged.

Now an extreme image. For a long infographic 1000 pixels wide and 6000 pixels tall, with the limit set to 6144, the computation gives 192 rows and 32 columns, exactly 6,144 patches, and the image becomes a thin 3072 × 512 strip. Shrink it to 224 × 224 the standard ViT way, and the 6000-pixel height is squeezed into 224, leaving one pixel out of every 27; probably not a single word on it could still be read.

Since the patch grid no longer has a fixed shape, the position embeddings have to change too. Pix2Struct uses 2D absolute positions. Each patch carries its own row and column index, each index looks up its own learnable embedding table, and both embeddings are added to the patch's projection. Row and column indices start at 1; 0 is reserved for padding patches, which attention masks out.

This has two benefits. Extreme aspect ratios aren't distorted, and to change resolution at inference time you only change the limit NN, with no retraining.

Screenshot Parsing

Original Figure 3: on the left is a toy web page titled Programming Survey, asking Your favorite programming language, with three options, Python, C++, and Java, each with a small icon, and a Submit button below. In the middle is the input version of the same page, with the options area framed by a blue box and the Python text and part of Java masked by red crosses. On the right is the simplified HTML to be output: <<<Python> <img_src=py_logo.png img_alt=Python>> <<C++> <img_src=cpp_logo.png img_alt=C++>> <<Java> <img_src=java_logo.png img_alt=Java>> <Submit>>.
Original Figure 3, Lee et al., from PDF page 4, CC BY 4.0.

The pretraining data comes from the URLs in the C4 corpus. Instead of using C4's already-extracted text, the authors re-crawled these pages themselves and saved the HTML source and screenshots, 80 million pairs in total, about a third of the number of documents in C4. Screenshots are 1024 pixels wide, with the height extending to fit the content.

Raw HTML is long and messy, far too much to decode as a target as it stands, so the authors simplify it first:

  1. Keep only visible nodes, or nodes with visible elements beneath them.
  2. When a node has no visible content of its own and only one child, replace it directly with its grandchildren, collapsing layers of empty nesting.
  3. Each node keeps only its text, image filenames, and alt text. Tag names, styles, and link URLs are all dropped; the authors say these can be left for future work.

The simplified DOM tree may still be too large. The authors find the largest subtree that “fits within a preset length once linearized” and use it as the target, drawing a box on the screenshot to tell the model which region to parse this time. That's the blue box in the middle of the figure.

Next comes masking. Following BART, random spans are chosen from this subtree's text until half of it is masked, red crosses are drawn over the corresponding spots in the screenshot, and the model has to write out the entire subtree, masked parts included.

In the figure's example, what the model has to output actually tests three things at once:

  • C++ isn't masked, so writing <C++> is doing OCR.
  • Python is masked, so writing <Python> means guessing from the Python logo beside it and the surrounding context; that's masked language modeling.
  • The image's alt text img_alt=C++ amounts to image captioning, with the whole web page available as context.

The authors' argument is that a web page's HTML already spells out its text, images, and layout structure, which amounts to free, clean annotation. Compared with Donut, which only asks the model to read the text in order, this objective forces the model to understand “which text belongs to which block, and how the blocks nest.”

Learn to Read First

Starting screenshot parsing from scratch, the authors found training unstable and slow to converge.

Their fix is a reading class first. Text snippets of up to 128 bytes are taken from BooksCorpus and rendered in random colors, random Google Fonts typefaces, and font sizes from 12 to 36 pt on a white background 640 pixels wide, and the model just has to copy the text out verbatim. This warmup stage runs for 30,000 steps with a sequence length of only 128 patches.

The authors also admit that this is pretty much a simplified version of Donut's pretraining.

For the main pretraining, the sequence length goes up to 2048 patches. Base then runs for another 270,000 steps with batch size 2048 on 64 TPUs; Large runs for 170,000 steps with batch size 1024 on 128 TPUs. The decoding length is 128 tokens, and target text is capped at 1024 characters.

Questions Drawn into the Image Too

Fine-tuning has to deal with the formats of all kinds of downstream tasks, and Pix2Struct's principle is to draw everything it can into the image.

  • Image captioning (TextCaps, Screen2Words): train directly on images and caption text.
  • Widget captioning (Widget Captioning): when the thing to describe is one particular button on the screen, draw its bounding box on the image.
  • Visual question answering (ChartQA, DocVQA, InfographicVQA, OCR-VQA): render the question as a header bar attached to the top of the image. For multiple choice (AI2D), the options are drawn in too.
  • Referring expressions (RefExp): given a description and a set of candidate components on the screen, find the one the description refers to. The authors make one image per candidate, drawing the box and the description on it, and have the model answer true or false; at inference, they pick the candidate with the highest “true” score.

A typical multimodal model opens a separate text input for the question. Pix2Struct has only one entrance, the image, so the question must first be drawn as pixels and then read by the model itself. The authors liken this to the habit that has held since GPT of concatenating all inputs into one sequence and handing it to a single model.

Discussion

Nine Tasks

The evaluation covers nine tasks in four domains, all using standard splits only, with no annotations from other datasets added. The “prior best” for each task is mostly a pipeline relying on external tools; the most important pixel-only baseline is Donut, which the authors fine-tuned themselves on tasks with no existing results.

TaskPrior best (method)DonutPix2Struct-L
ChartQA45.5 (VisionTaPas)41.858.6
AI2D38.5 (DQA-NET)30.842.1
OCR-VQA67.5 (LATr)66.071.3
RefExp90.8 (UI Bert)–94.2
Widget Captioning97.0 (PLC)127.4136.7
Screen2Words64.3 (VUT)56.4109.4
TextCaps160.4 (PaLI)74.495.5
DocVQA84.7 (UDOP)67.576.6
InfographicVQA47.4 (UDOP)11.640.0

Compiled from Table 1 of the paper; method names for the prior best come from Table 3 of the paper. Metrics follow each dataset's original definition: relaxed accuracy for ChartQA, exact match for AI2D, OCR-VQA, and RefExp, CIDEr for the captioning tasks, and ANLS for the two document tasks.

This table can be read in three parts.

  1. Mobile UIs and illustrations. Pix2Struct takes the best result on five tasks, six counting Widget Captioning. Screen2Words jumps from 64.3 to 109.4; ChartQA goes from 45.5 to 58.6, and the previous best, VisionTaPas, first had to convert the charts into tables with a tool. Models in these domains had lacked large-scale pretraining, and web screenshots happen to fill that gap.
  2. Donut trails across the board, by 5.3 to 53 points on the eight tasks it has scores for. InfographicVQA is the most extreme, with Donut at just 11.6; the authors speculate that because Donut resizes images to a fixed aspect ratio, extremely long infographics become illegible once shrunk.
  3. On documents and natural images, Pix2Struct loses. Its 76.6 on DocVQA is below UDOP's 84.7 and LayoutLMv3's 83.4, models that use OCR and were also pretrained on IIT-CDIP scanned documents. The authors acknowledge that DocVQA is so text-dense that text-only models already come close to the best results, so the image can only help so much. On TextCaps, it loses to GIT2 and PaLI, trained on more than ten billion image-text pairs.

Also, Base saw about three times as much data as Large (270,000 steps × 2048 vs. 170,000 steps × 1024), yet Large is still better on every task. The authors believe there's room to scale further.

Remove Screenshot Parsing and Nothing Is Left

The ablations use the Base model with 100,000 pretraining steps in total, compared on three validation sets:

PretrainingDocVQAWidget CaptioningTextCaps
Full (30K warmup + 70K screenshot parsing)67.8137.584.2
No warmup56.2128.071.7
No masking55.7129.477.4
No screenshot parsing (warmup extended to 100K)12.235.124.2

Compiled from Table 2 of the paper.

Warmup and masking contribute about equally; remove either one, and DocVQA drops 11 to 12 points. Removing screenshot parsing is in a different league entirely, with DocVQA falling from 67.8 to 12.2. A model that has only learned to copy text in order does poorly on almost every downstream task.

This also directly backs up the authors' criticism of Donut. “No screenshot parsing” here amounts to reading-only pretraining; the setup isn't identical to Donut's, but it points the same way.

Resolution

The authors examine the effect of variable resolution with two sets of experiments. Comparing three input schemes during warmup, variable resolution with the aspect ratio preserved learns fastest; the version that preserves the aspect ratio but pads with white borders is slowest, because so much padding wastes the effective resolution; and the standard ViT version that simply stretches the image falls in between.

The other, in the appendix, looks at how resolution affects DocVQA:

Original Figure 5: in the left plot, the horizontal axis is input sequence length (128 to 16384, log scale), with effective pixel counts from 2^15 to 2^22 marked along the top, and the vertical axis is DocVQA ANLS. The orange line, Pix2Struct-base, starts at about 10 points with 128 patches and climbs to about 56 at 1024, about 69 at 2048, and about 72 at 4096; the green line, Donut, plotted by effective pixel count, rises from 41 points at about 2^19 pixels to about 60 at 2^22. Two dashed black lines mark the resolutions commonly used for ViT pretraining and fine-tuning. The right plot shows samples processed per second; Base falls from about 255 at 128 patches to about 62 at 4096, and Large from about 80 to about 20.
Original Figure 5, Lee et al., from PDF page 13, CC BY 4.0.

Start with the left plot. The orange line is Pix2Struct-base, read against the sequence length at the bottom; the green line is Donut, read against the effective pixel count at the top. The two dashed black lines mark ViT's usual 224 × 224 pretraining and 512 × 512 fine-tuning resolutions.

At 1024 patches (about 512 × 512), Pix2Struct scores only around 56, reaching 72 only at 4096. The authors say returns start to diminish noticeably only past about a million pixels. In other words, the resolutions ViTs typically use are nowhere near enough for reading documents.

The right plot is the price. Raising the sequence length from 128 to 4096 drops Base's throughput from about 255 documents per second to 62, and Large's to just 20. The paper's discussion section also acknowledges that resolution is the biggest bottleneck for pixel-only models; OCR pipelines can use low-resolution images because the text has already been handled by a dedicated text encoder.

Pretraining Is a Black Box

Pix2Struct's official repo released pretrained weights for Base and Large, fine-tuned weights for the nine tasks, and the fine-tuning code. On the pretraining side, the README says:

We are unable to release the pretraining data, but they can be replicated using the publicly available URLs released in the C4 dataset.

The data can't be shared, but the URLs are public, so you can rebuild it yourself. As for how to rebuild it, that code isn't in the repo.

In March and April 2023, issue #24 and #27 each asked for the code that generates screenshots and HTML from C4 URLs; in May, Ross Wightman, author of timm, wrote in #34 about wanting to build a reference implementation on open data and asked about the rules for simplifying HTML, the length of the warmup data, and how the masked spans are chosen. In August, #41 and #42 asked about the same details. Five issues, and to this day not a single reply from the authors (the URLs are public; the rest is left as an exercise for the reader).

A 2024 CVPR paper (S4, arXiv 2403.03346) actually tried to pick up where Pix2Struct left off. Rerunning fine-tuning from the official weights with a smaller batch, they got ChartQA 54.3, RefExp 91.7, Widget Captioning 131.1, and Screen2Words 105.5, 0.5 to 2 points off the paper, so the fine-tuning part is reproducible. But when they crawled 2 million web pages from Common Crawl themselves and continued pretraining with the same screenshot parsing objective, ChartQA actually dropped to 47.4. They put it down to data size, distribution, and Pix2Struct's filtering; in their words, “the filtering process remain unclear for Pix2struct.”

As for the pretrained weights themselves, issue #38 has been open since July 2023. Users fed screenshots to pix2struct-large on Hugging Face hoping to see it write HTML, and got only <img_src=image>; after upgrading the library, that became <>. Someone tried the screenshot of the pricing-plan page from the paper and also got <>. A string of +1s follows, the last in January 2025, and the authors never showed up.

There's one more detail in the evaluation. ChartQA uses relaxed accuracy, where a numeric answer counts as correct if it's within 5% of the ground truth. The official relaxed_correctness applies this rule whenever the string can be converted to a number, and years are no exception. As issue #35 points out, with a ground truth of 2010 and a prediction of 2008, the relative error is 0.1%, so it counts as correct (by this metric, 2008 and 2010 are the same year). The paper doesn't report how many ChartQA questions have years as answers, so there's no telling how much this leniency contributes to the 58.6. This issue hasn't been answered either.

Conclusion

Pix2Struct shows that a model that takes in only pixels and puts out only text can, by pretraining on web screenshots, far outperform the specialized pipelines in domains like charts and mobile UIs that lack pretraining data. The ablation also makes it clear that having the model parse web page structure is far more useful than having it read text in order.

In document understanding, its turn hasn't come yet. On DocVQA, UDOP and LayoutLMv3, which use OCR and were pretrained on scanned documents, still lead by 7 to 8 points.

What later models borrowed from this paper most often turned out to be two seemingly small design choices. One is the input scheme that preserves the aspect ratio and scales to a patch budget, which Google's later NaViT cites as a precedent right at the start of its paper; the other is drawing the question directly onto the image, so that all inputs go through one entrance. Before long, Fangyu Liu, Kenton Lee, Mandar Joshi, and others built on it to make MatCha and DePlot, which specialize in charts.

As for the pretrained weights that learned to write screenshots back into HTML, ask them today and you'll most likely get an empty pair of brackets.