Chargrid: Towards Understanding 2D Documents
- Publication
- EMNLP 2018Conference
- First submitted to arXiv
- arXiv:1809.08799
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{documentunderstandingchargrid2018,
title = {{Chargrid: Towards Understanding 2D Documents}},
author = {Anoop Raveendra Katti and Christian Reisswig and Cordula Guder and Sebastian Brarda and Steffen Bickel and Johannes Höhne and Jean Baptiste Faddoul},
year = {2018},
eprint = {1809.08799},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1809.08799}
}
Hand an invoice to a language model, and the first step is usually to flatten its text into a single line.
OCR spits out the characters top to bottom and left to right, joins them into one long string, and passes that to an NLP model. For news articles or novels this loses almost nothing. Invoices are another story.
The sample invoice in this paper's Figure 1 (we'll see the original shortly) has three rows of line items: a consulting service, an extra fee, and travel costs. The second row's description takes two lines, with a small indented line, "24h Service," under "Extra Fee." Joined in reading order, the middle part looks roughly like this:
3001 Extra Fee 1.00 HR $ 70.00 $ 70.00 24h Service 9001 Travel costs 1.00 TR $ 40.00 …
"24h Service" is wedged between the amount of the row above and the item number of the row below. A person looking at the original sees at a glance that it belongs to Extra Fee, because it sits right below Extra Fee; once the text is flattened, "right below" is gone. The quantity column is the same. "1.00" is a quantity because it lines up vertically with "Qty." in the table header, and that can't be found anywhere in a string of text either.
The authors are seven members of SAP's machine learning R&D team in Berlin, with Anoop R Katti and Christian Reisswig as joint first authors. SAP makes enterprise management software, and invoices are exactly the documents its customers handle every day. Their chargrid doesn't flatten the document; it fills each character back into its position on the page.
Defining the Problem
At the time, there were roughly two ways to handle documents like these.
The first is NLP. Flatten the OCR output into a sequence of characters or words, then do sequence labeling. The baseline the authors compare against is Palm et al.'s CloudScan from 2017, a multi-layer bidirectional GRU that reads a string of characters and outputs a field label for each one. As the example above showed, on tables and multi-line fields this path loses "who sits right below whom."
The second is computer vision. Treat the page as an image and give it to a CNN for segmentation or detection. The 2D structure survives, but the CNN sees grayscale strokes and has to teach itself to read from pixels before it can tell "Total" from "Tax." The authors argue this makes the model more complex and needs far more training data.
Some work has also mixed the two. The closest is Yang et al.'s 2017 MFCN, which does layout segmentation and, in the last layer of its decoder, attaches each sentence's embedding vector to the pixel features inside that sentence's extent. Text information gets in, but only at the very end of the network, and as one vector per sentence.
Can a CNN receive the already-read characters from its very first layer while keeping each character's position on the page? That's the question chargrid sets out to answer.
Solving the Problem
Filling Characters Back into the Grid
chargrid's raw material is a set of character boxes. Each character comes with a box , that is, its top-left corner plus width and height, in pixels of the original page. These boxes can come from OCR, or straight from the layout information of a PDF or HTML file.
Next, build an integer map the same size as the page:
is a pixel on the page; if it falls inside the -th character box, it gets . maps characters to integers, for example a→1, b→2, c→3, with 0 for the background.
Take "1.00" on the sample invoice. Each of the four characters has a box: every pixel in the box of "1" gets , the box of "." gets , and so on; the gaps between characters, and every part of the page without text, are all 0. The whole invoice turns into what you see on the right of the figure below, colored bars on a black background, with each color standing for a character index.

There are two details here. In theory, character boxes don't overlap; in practice, the boxes from OCR often overlap at the corners, and then a pixel goes to the character whose box center is closest. Also, the bigger the character, the more cells it occupies. In NLP a character is one token; here a character may cover dozens of pixels. The authors see this as a plus: font size gets encoded along the way, and large text such as the total amount or a title naturally stands out more on the grid.
Why It Can Shrink So Much
You can't shrink an ordinary image carelessly. Shrink an "8" that occupies 10 × 10 pixels down to 1 × 1, and its strokes are gone; the model will never recognize it again.
chargrid is different. Every pixel in a character box has the same value, and that value is itself the "8." As long as each character still occupies at least one cell after shrinking, no information is lost. The paper's example is that if the smallest character occupies 10 × 10 pixels, the whole map can be shrunk by a factor of 10 × 10, and the computation for training the network drops sharply along with it.
In practice it happens in two stages, and the order matters.
- First, shrink the integer indices with nearest neighbor to twice the target resolution. Indices are categorical values and can't be interpolated: average "a = 1" and "c = 3" and you get 2, which certainly doesn't turn into a "b." Stopping at twice the target instead of going all the way in one step keeps even the smallest characters from being skipped at this stage.
- Convert to one-hot, then shrink with bilinear interpolation to the final 336 × 256. Now each channel means "this character is here or not," so the interpolated values are proportions and make sense.
The authors note that you could also convert to one-hot first and shrink all the way with bilinear interpolation in one go; the two-stage version is just cheaper to compute.
The character vocabulary keeps only the most common characters, plus background and an "unknown character," for in all, so after one-hot the input is a tensor. Landscape pages are simply squashed into the same size; the authors say this did no harm, so they stuck with it.
chargrid-net
With a input, what comes next is a segmentation network, which the authors call chargrid-net:

The taller a block, the higher the feature-map resolution; the wider, the more channels. Let's follow the input through.
The encoder is five VGG-style blocks, each with three 3 × 3 convolutions (convolution, BN, ReLU) and spatial dropout at the end. The first convolution in a block has stride 2 and does the downsampling, and the channel count doubles each time; the authors compared the two and found stride-2 convolution slightly better than max pooling. Working out the shapes from the paper's description:
- block 1:
- block 2:
- block 3: , dilation
- blocks 4 and 5: no further downsampling, staying at , with channels capped at 512 and dilations
Each cell at the deepest level corresponds to 8 × 8 character-pixels of the input. The last two blocks stop shrinking and switch to dilated convolutions, so the receptive field keeps growing while the resolution stays put.
There are two decoders, identical in structure up to the last stage. Each stage first takes in the encoder features at the same resolution (lateral connections), tidies the channels with a 1 × 1 convolution, doubles the size with a stride-2 transposed convolution, and follows with two 3 × 3 convolutions, halving the channel count. After three upsamplings, it's back at 336 × 256.
- Semantic segmentation branch: the final convolution has no BN, has a bias and goes through softmax, outputting the class of each character-pixel.
- Box regression branch: together with the encoder, it forms a one-stage detector with Faster R-CNN-style anchors and regression targets. Each position outputs foreground/background scores and box coordinates, where is the number of anchors per position.
Why Boxes Too?
After segmentation, every character already has a label. So why boxes as well?
Invoice fields come in two kinds. The number, date, total amount, vendor name and vendor address are five header fields that appear only once per invoice, so collecting the characters assigned to one class gives the answer. Line items are different: the description, quantity and amount fields repeat row after row. The sample invoice has three rows, and all three "quantities" get assigned to the Line-item Quantity class. From the segmentation alone, you know there are three quantities on the page, but not which quantity goes with which description.
The authors let the boxes handle "rows" and the segmentation handle "columns." In training, each box spans one entire row of line items, and the characters inside the box segmented as Quantity are that row's quantity. The box for the Extra Fee row also wraps the "24h Service" beneath it, so the two lines end up under the same description, which is exactly what the flattened string at the start couldn't manage.
Counting background, segmentation has 9 classes in all: 5 header fields, 3 line-item fields and 1 background.
Loss and Class Weights
The total loss is three equally weighted terms:
Segmentation uses cross-entropy, box foreground/background uses binary cross-entropy, and box coordinates use Huber loss.
The trouble is extreme class imbalance. Most of an invoice is blank space and irrelevant text, and the fields to extract are only a small handful. The paper says that early on, without class weights, both segmentation and box regression performed poorly. They also tried focal loss and in the end found fixed class weights more effective, using ENet's formula:
is the class's share of the training data and is a constant; this paper uses (ENet originally used 1.02).
Plug in some numbers to get a feel for it. Suppose background covers 95% of the pixels and some field covers only 0.1%:
- Background:
- Rare field:
The rare class weighs about 17 times as much as background. However small gets, the weight never exceeds , unlike a plain reciprocal, which blows up on extremely rare classes.
Another imbalance sits at the data level. About half the invoices have fewer than three line items, so box regression rarely sees "a tall stack of rows to cut apart." In training, the authors sampled invoices with more than three line items more often; the paper says this clearly improved box regression accuracy, without giving numbers.
The other settings: TensorFlow 1.4, SGD (momentum 0.9, learning rate 0.05, weight decay ), spatial dropout 0.1, and random cropping for data augmentation (after downsampling, pad each side by 16 cells, then crop back to the original size at a random offset). Batch size 7, about 360,000 iterations, and three days on one Tesla V100 to converge.
Discussion
Data and Metric
The data is 12,000 scanned invoices from a large number of different vendors, covering many languages. English is the most common, with plenty of French, Spanish, Norwegian and German too. They're split into 10,000 for training, 1,000 for validation and 1,000 for testing, and each vendor appears in only one split. Most vendors have just one invoice in the whole dataset, and even the most frequent has only 6, so the model has seen almost none of the test-set layouts.
The labeling took a lot of effort. Each invoice went through three annotators plus one reviewer; they looked at 35,000 invoices in all and kept only 12,000 clean ones. OCR is the open-source Tesseract v4.
The metric is modeled on word error rate in speech recognition. For each field, pool the predictions over the whole test set and count how many insertions, deletions and modifications it takes to turn them into the ground truth:
is the total number of instances of that field in the test set, and matching is done per string. The score tries to measure "how much a person still has to fix after using this system," so it can go negative, meaning the model's extra errors cost more effort than copying out the whole field by hand.
OCR typos don't count, because the ground truth and the predictions use the same OCR output. What's measured here is extraction; how well the text was recognized is a separate question.
Main Results
There are four points of comparison:
- sequential: the authors' own reimplementation of CloudScan, a bidirectional GRU that reads character sequences. The authors also tried feeding in each character's coordinates and reported "negligible returns," so they went with the simple version.
- image-only: exactly the same network as chargrid-net, except that the input is the original page image shrunk to 336 × 256.
- hybrid-C64: two encoders, one taking the chargrid and one taking the image, with lateral connections from both feeding the decoder; each encoder has base channels .
- hybrid-C32: the same, but the two encoders have only each while the decoder stays at 64, to control the parameter count.
The two tables below are compiled from the paper's Table 1, and the numbers are the Accuracy (%) from the previous section. Header fields first:
| Model | Number | Total | Date | Vendor | Address |
|---|---|---|---|---|---|
| sequential | 80.98 | 79.13 | 83.98 | 28.97 | 16.94 |
| image-only | 47.79 | 68.91 | 45.67 | 19.68 | 13.99 |
| chargrid-net | 80.48 | 80.74 | 83.78 | 36.00 | 39.13 |
| hybrid-C32 | 74.85 | 77.93 | 80.40 | 32.00 | 31.48 |
| hybrid-C64 | 82.49 | 80.14 | 84.28 | 34.27 | 36.83 |
Then the line-item fields:
| Model | Description | Quantity | Amount |
|---|---|---|---|
| sequential | −0.01 | −0.18 | 0.22 |
| image-only | 49.50 | 46.79 | 63.49 |
| chargrid-net | 52.80 | 65.20 | 65.57 |
| hybrid-C32 | 46.27 | 64.04 | 63.25 |
| hybrid-C64 | 48.81 | 64.59 | 64.53 |
A few things to read side by side:
- Number, total amount and date: chargrid-net and sequential are nearly tied (80.48 vs 80.98, 80.74 vs 79.13, 83.78 vs 83.98). These fields are a single word, usually right after a keyword such as "Number:" or "Date:", so the flattened text is enough.
- The three line-item columns: sequential falls to around 0, with description at −0.01 and quantity at −0.18. By the metric's definition, the amount of manual fixing is about the same whether you use it or not. chargrid-net gets 52.80, 65.20 and 65.57 on the same three columns, and the gap is the "right below" from the opening.
- image-only does badly on small fields that have to be read before they can be located, with number at 47.79 and date at 45.67; on large blocks that layout alone can find, the gap is much smaller, with line-item amount at 63.49 vs 65.57 and description at 49.50 vs 52.80. It can see where things are but can't understand what they say.
- The image adds nothing extra. hybrid-C64 carries an entire extra image encoder, yet it wins slightly only on the number and date columns, and loses slightly to chargrid-net on the total amount, vendor name, vendor address and all three line-item columns. Shrink the two encoders to C32 and almost every column drops. The authors conclude that the discriminative information comes mainly from the chargrid branch, and they make a point of adding "at least in the case of our invoice dataset."
- Vendor name and address: every model scores low, and the best manage only 36.00 and 39.13. The paper brings up the vendor address only in its conclusion, as an example of a field that needs both the text and the layout, and never analyzes why the scores are so low; these fields are multi-word, multi-line and come in every format imaginable, and they are the only fields in the table where even chargrid-net can't extract half.
Failure Cases
The authors also picked three examples where extraction went wrong:

- Example 1: the model counts several unrelated rows of text as line-item descriptions and misclassifies some characters, which in turn makes the header fields above the line items come out wrong. Both the mask and the boxes are wrong.
- Example 2: the mask is roughly right, but two of the four line items get no box, so their characters can't be assigned to a row.
- Example 3: two adjacent multi-line items are crammed together, and the boxes don't cut them apart.
The most common error is failing to separate line items with unusual formats. The authors also admit that the ground truth itself is sometimes debatable; where a line-item description ends, for instance, is something human annotators might not agree on either.
The Cost
The 2D representation isn't free. chargrid-net takes three days to converge, while the sequential model is done in a few hours. The dimensionality of the input data goes up sharply, and after one-hot nearly every position is 0, so it's extremely sparse. Sparse input like this is common in NLP, but for segmentation networks that had only ever been fed natural images, it was something new.
Another limitation is the data. The whole paper rests on a single dataset, these 12,000 invoices that SAP collected and labeled itself, and it isn't public; the code isn't public either, and the metric is custom. Outsiders have no way to recompute the numbers in the tables on the same data.
The community did try. The most-starred unofficial implementation on GitHub, antoinedelplace/Chargrid, redid it on the public SROIE receipt data. The Results section of its README says "[TODO]," and the last update stops in March 2020. Issue #7 asked in June 2020 why the predictions were wrong after training and when results would be shared; others followed up with the same question in 2021, and there has been no reply to this day (so far, the only reproduction result outsiders can see is a TODO).
A 2021 paper on evaluating invoice field extraction (2106.14624) says plainly in its abstract that existing models were trained either on unpublished data or only on receipts, so the authors first wrote a tool that generates documents from templates and then rebuilt Chargrid themselves. The result its abstract reports is that the bounding box regression decoder improves performance only on fields that aren't rectangular. The Chargrid paper spends a whole section explaining why boxes are needed; by this outside result, the boxes only help on fields like the line items, which span several lines and have irregular shapes.
Conclusion
chargrid puts the characters OCR has read back onto the page, exactly as they were, and hands the result to a segmentation network. On the invoice's line-item fields, which the sequence model can barely extract at all, chargrid-net gets 52.80 to 65.57; on single-word fields such as the number and date, the two tie. Layout helps on fields like line items, which repeat row after row and only make sense through vertical alignment.
After that the road forked. One branch kept laying grids: SAP's own BERTgrid replaced the one-hot vectors in the grid with BERT vectors, followed by VisualWordGrid and ViBERTgrid. The other went back to sequences and gave each word coordinates. The chargrid authors tried adding coordinates to the GRU and said it didn't help much; a little over a year later, LayoutLM turned coordinates into BERT position embeddings and added large-scale pretraining, and only then did that path pay off.
If you also have a categorical 2D map to shrink, whether characters or segmentation labels, shrink it with nearest neighbor first and interpolate only after converting to one-hot. Run bilinear directly on the indices, and a nonexistent "b" pops up between "a" and "c."