Back to paper library
Paper notesarXiv 2023ICLR 2024

Nougat

Going in Circles

Original paper

Nougat: Neural Optical Understanding for Academic Documents

Paper authors

Lukas Blecher · Guillem Cucurull · Thomas Scialom · Robert Stojnic

Publication
ICLR 2024Conference
First submitted to arXiv
arXiv:2308.13418
Cite this paper · BibTeX

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

@misc{textspottingnougat2023,
  title = {{Nougat: Neural Optical Understanding for Academic Documents}},
  author = {Lukas Blecher and Guillem Cucurull and Thomas Scialom and Robert Stojnic},
  year = {2023},
  eprint = {2308.13418},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2308.13418}
}
On this page

Feed a paper's PDF to an ordinary OCR engine, and most of the text comes out fine, but the math often falls apart into a heap of symbols.

It's easy to see why. In xi2x_i^2, the subscript ii and the superscript 22 are stacked to the right of xx; a fraction puts its numerator above its denominator. Line-by-line OCR treats them as ordinary text, and the spatial relationships are lost. The PDF itself doesn't help much either, since it records “which glyph is drawn where on the page,” and the original LaTeX structure of the math was already thrown away at compile time.

Nougat, introduced by Meta AI in August 2023, tries to solve this in one stroke, taking an image of a paper's page and directly outputting markup text with LaTeX math and tables. The code is open source under the MIT license, and the model weights are released under CC BY-NC.

Defining the Problem

Each existing tool fell short somewhere:

  • OCR engines such as Tesseract are good at detecting and classifying individual characters or words, but they work line by line and can't make sense of spatial relationships such as superscripts and subscripts.
  • GROBID parses born-digital paper PDFs into XML and handles bibliographic data well; for math, it keeps only the Unicode characters found in the PDF.
  • pdf2htmlEX converts PDFs into HTML that looks the same, but it can't recover the meaning of the math either.

The authors wanted a model that looks only at the page image. Working from the image alone means old scanned papers and books can be handled too; outputting markup directly means the structure of math and tables can be preserved.

Solving the Problem

Architecture: Borrowed from Donut

Nougat architecture: a document page image is encoded by a Swin Transformer into a latent representation z, and a Transformer decoder autoregressively outputs tokens; example output text is shown on the right
Figure 1 from the paper, excerpted from page 2 of the v1 PDF, CC BY-SA 4.0.

The architecture is simple and borrows from Donut (2021):

  1. Encoder: the page's margins are cropped off, and it is resized and padded to a fixed 896×672 (an aspect ratio between US Letter and A4), and a Swin Transformer turns it into a sequence of patch vectors zz.
  2. Decoder: a 10-layer mBART decoder reads zz through cross-attention and outputs tokens autoregressively, up to 4,096 of them. The tokenizer is borrowed from Galactica, a model built for scientific text.

The whole model has about 350 million parameters. The authors also tried a smaller 250-million-parameter version whose decoder has only 4 layers. Inference uses greedy decoding.

There is no text detection here and no OCR preprocessing of any kind. How the characters get read is left entirely for the network to learn.

Data: Cutting LaTeX Source into Pages

The biggest engineering effort went into the data. Training “page image → markup text” requires a large amount of paired data, and none existed at the time.

The authors collected the LaTeX source and compiled PDFs of 1,748,201 papers from arXiv, added a portion of open-access papers from PubMed Central, and, for pretraining, also used OCR text from the Industry Documents Library.

The processing pipeline:

  1. Convert LaTeX to HTML with LaTeXML, which along the way expands custom macros, normalizes whitespace, standardizes tables, and resolves references to the correct numbers.
  2. Convert the HTML into a lightweight markup language that keeps headings, bold and italic text, algorithms, inline and display LaTeX math, and LaTeX tables.
  3. Split the full source into pages and match each one to the corresponding page image of the PDF.

The third step is the hardest. LaTeX page breaks are decided by the compiler, and the source contains no page-break markers; figures and tables also often end up somewhere else in the PDF than in the source. The authors handle it in two passes:

  • Coarse split: extract the text of each PDF page with MuPDF and train a TF-IDF plus linear SVM classifier to predict which page each paragraph of the source belongs to. Ideally this produces a staircase-shaped sequence of page numbers; in practice it is noisy, so they use Gini impurity, as in decision trees, to find the best split points.
  • Fine split: near each predicted split point, fuzzy-match the source against the last few sentences of the previous PDF page and the first few sentences of the next to find the exact position. A page enters the dataset only if its two split points average a score of at least 0.9.

In the end, about 47% of the pages passed the filter.

Making Digital PDFs Look Scanned

The training data consists entirely of born-digital papers, yet the model has to handle scans. The authors used Albumentations to add a series of image perturbations such as erosion, dilation, Gaussian noise, blur, binarization, compression, grid distortion, and elastic transforms.

They also added perturbations on the text side; we'll come back to what that does later.

Discussion

Results on the arXiv Test Set

Table: Excerpted from Table 1 of the paper.
MethodCategoryEdit distance ↓BLEU ↑F1 ↑
Embedded PDF textAll0.25565.879.2
GROBIDAll0.31255.673.0
Nougat baseAll0.07189.193.1
Nougat basePlain text0.05891.295.7
Nougat baseMath0.12856.976.5
Nougat baseTables0.21169.778.0

Overall, Nougat's edit distance is only about a quarter of GROBID's. Of the three content types, math is the hardest, with more than twice the edit distance of plain text.

The authors explain that math scores are inherently low because the same expression can be written many ways in LaTeX, such as the order of subscripts and superscripts, \frac versus \over, or \mathbf versus \boldsymbol, which render identically but produce different strings.

The small model (250 million parameters) scores almost the same as the large one.

Stuck in Repetition

The authors are candid about what failure looks like.

The model sometimes falls into repetition. In the simplest case, it outputs the same sentence or paragraph over and over; it may also alternate between two sentences, changing a few words each time, so that strict repetition detection misses it. In the references section, the model may even count up the numbering on its own and keep writing. Once it enters this state, it can't get back out.

This happens on about 1.5% of the pages in the test set, and more often on documents outside the training domain. The authors observe that repetition usually starts after the model has made a mistake.

So the fix is to let the model see its own mistakes during training. During training, they randomly replace some correct tokens with arbitrary ones, and the replacement continues until a newly sampled random number exceeds 10%. The model thus learns to keep reading when the preceding text contains an error, instead of being carried off by the wrong token. The authors saw no drop in overall performance but a clear reduction in repetition; on out-of-domain documents, failed page conversions fell by 32%.

Detecting Repetition

Reducing repetition alone isn't enough. The decoder generates up to 4,096 tokens, and once it is stuck in a loop, it runs all the way to that limit for nothing. So the authors also designed a detection method.

Two repetition-detection examples with three plots each: the maximum logit of each token, the sliding-window variance, and the variance from that position to the end. The top row falls into repetition after about token 1,000, and its variance drops sharply below the threshold; the bottom row is a normal sample whose variance stays high throughout
Figure 6 from the paper, excerpted from page 8 of the v1 PDF, CC BY-SA 4.0. The top row is a sample with repetition and the bottom row a normal sample; the dashed lines mark where repetition starts and the decision threshold.

In the top-left plot, the horizontal axis is the index of the generated token, and the vertical axis is the largest logit at each step. Before roughly token 1,000, the points are widely scattered; after that, they all crowd into a band between 17 and 18. The normal sample in the bottom row stays widely scattered throughout.

Intuitively, with normal text the model's confidence rises and falls from step to step; once it is stuck in repetition, it grows more and more certain about the next token, and the maximum logit flattens out. The authors turn this into a two-step computation:

  1. Over the maximum-logit sequence ℓ\ell, slide a window of size B=15B=15 and compute the variance within each window, VarWinB\mathrm{VarWin}_B (the middle plot).
  2. Then, from each position to the end of the sequence, compute the variance of those variances, VarEndB\mathrm{VarEnd}_B (the right plot).

If VarEndB\mathrm{VarEnd}_B drops below 6.75 and stays there until the end, the output is classified as repetitive.

Three numbers give a feel for it (illustrative values, not data from the paper). In a normal stretch, the maximum logits might be 20, 25, and 18, with a variance of about 8.67; during repetition, they might be 17.0, 17.2, and 16.9, with a variance of only 0.016. With a gap of several hundredfold, the two are easy to tell apart.

During inference, the “end” isn't visible yet, so the authors use only the most recent 200 tokens and half the threshold, checking as generation proceeds; once generation finishes, they run the check again over the full sequence.

What Users Ran Into

Issue #11 on Nougat's GitHub is a report from August 30, 2023, in which a user tested a scan of the 1935 EPR paper from Physical Review. The first page came out fine, pages two through four all triggered a “Found repetitions” warning, and the output for them was just [MISSING_PAGE_EMPTY:1]. facebookresearch/nougat#11

That is repetition detection at work, marking a page judged to have failed as missing instead of outputting it as a page of repeated text. For the user, a missing-page marker at least signals that this page needs separate handling.

The official README also states plainly that English papers work best, other Latin-script languages might work, and Chinese, Russian, Japanese, and the like won't.

What to Know When Reading This Paper

The authors list several points in their limitations section:

  1. Repetition remains the biggest problem, and the paper leaves it to future work.
  2. Almost English only. Special characters in other Latin-script languages are replaced by the closest English letter; non-Latin scripts fall into repetition immediately.
  3. One page at a time. Consistency across pages isn't guaranteed. The most obvious case is the references: the numbering sometimes skips, or picks up numbers the original doesn't have.
  4. It is slow. On a single A10G, processing 6 pages at a time takes 19.5 seconds per batch on average, whereas GROBID can process 10.6 PDFs per second.

Conclusion

Nougat recasts OCR for academic papers as a generation task: “look at a page, write a page of markup.”

  1. A simple architecture: a Swin Transformer encoder plus an mBART decoder, with no OCR preprocessing.
  2. Data engineering takes center stage: page-level training data cut from the LaTeX source of 1.75 million arXiv papers, using a classifier and fuzzy matching.
  3. Math can be read end to end into LaTeX for the first time, with a much lower overall edit distance than GROBID.

It also laid out early on the typical ailments of generative OCR, including falling into repetition, replacing rare characters with common letters, and adding reference numbers that don't exist. The authors didn't stop at reporting scores; they also built countermeasures, injecting errors during training and detecting repetition during inference.

Once a page of text is handed to a language model to “write,” it will try its best to make the writing flow. When it can't go on, it's better to make it stop than to let it keep writing.