Rules Over Structure, Not Geometry: Grammar-Verified Document Extraction Under Layout Shift

Hand-written rules for reading documents fail for a specific reason. They are written over geometry, such as "the total is the rightmost number below the word TOTAL," and geometry is what changes when a receipt is photographed at an angle, a form is redesigned, or a table loses its borders. Classical grammar-based sentence parsers fail the same way: one unmodeled construction and the parse returns nothing. Neural layout models fixed coverage by learning geometry from data, but they gave up the property that made rules attractive. When a rule system produces an answer, the answer is usually right, and when it cannot, it says so. This note proposes to keep both properties by moving the rules to a different level. A neural spatial parser absorbs the layout variation and proposes several candidate structures. A small grammar, written over the logical output rather than the page, checks whether each candidate is a well-formed document of the expected kind. For a receipt, well-formed means that line items have a name, a count and a price, that price times count is consistent, and that the subtotal equals the sum of the items. The grammar then picks the best-scoring candidate that passes, or it abstains.

The claim is that rules over logical structure do not suffer the coverage collapse of rules over geometry, because a receipt's logical structure stays the same when its layout is warped. We therefore expect that whether the grammar accepts an output is a better signal of correctness than the neural model's own confidence, and that this advantage grows as layouts drift further from training. If this holds, a practitioner gets something current document extractors do not offer: a precision guarantee on the documents the system accepts, whose coverage degrades smoothly rather than collapsing on new layouts.

Core Claim and What Is New

The parsing literature already shows the trade this proposal exploits. Hand-built grammars such as the English Resource Grammar top out near 89% coverage. Data-driven parsers reach 100% (Accurate SHRG-Based Semantic Parsing; Robust Incremental Neural Semantic Graph Parsing). Yet the grammar-based parser keeps higher precision on the sentences it does parse. An Integrated Architecture for Shallow and Deep Processing raised deep-parser coverage from 12.5% to 22.1% on NEGRA by letting shallow statistical components scaffold the grammar. That work motivates the idea: robust shallow components plus a precise deep checker beat either alone. It also constrains the design, since even with scaffolding, a grammar that must derive the raw input covered barely a fifth of real text. We do not ask the grammar to derive the page. We ask it only to derive the output graph, which is a much smaller and much more regular object.

The closest document work handles output validity through heuristics or through format constraints. Spatial Dependency Parsing for Semi-Structured Document Information Extraction (SPADE) predicts a graph over text tokens using relative distances and angles. It has two kinds of edge: one links tokens within a field, the other groups fields hierarchically. SPADE decodes this graph with deterministic pruning ("Tail Collision Avoidance," worth about 1 F1 on CORD). That pruning only enforces local graph consistency and knows nothing about what a receipt is. Entity Relation Extraction as Dependency Parsing in Visually Rich Documents (SERA) imposes a single-parent tree constraint, which is a grammar of sorts but one too weak to catch semantic errors and too strict for structures where one entity has several parents. GenKIE: Robust Generative Multimodal Document Key Information Extraction uses constrained beam search to keep generated outputs in template form, which constrains surface format rather than cross-field consistency. Schema-Driven Information Extraction from Heterogeneous Tables (INSTRUCTE) comes closest in spirit. It checks a language model's cell-by-cell output against a rule-based cell detector and re-prompts when the model loses its place. But it works only on clean markup (LaTeX, HTML, CSV, XML), and its rule tracks traversal position, not the meaning of the extracted record.

Our proposal differs from all four in three ways. The rules are compositional and semantic, including arithmetic. They are applied to a ranked list of candidate graphs from a spatial parser over scanned images. And acceptance by the grammar is used explicitly for selective prediction, so we report precision as a function of coverage rather than a single F1.

Research Program

The system has three parts. The first is a SPADE-style spatial graph parser, retrained on each benchmark. We modify its decoder to output the top $k$ candidate graphs rather than one, using beam search over edge decisions ranked by summed edge log-scores.

The second is a document grammar. It is an attribute grammar, meaning a context-free grammar whose rules carry checkable conditions over field values. Its symbols are field types, such as item, item-name, item-price, subtotal and total. Its conditions are numeric or format checks, such as whether a count times a unit price equals the line price within rounding, whether the item prices sum to the subtotal, and whether a field parses as a date.

The third is a selection rule. The system returns the highest-scoring candidate the grammar accepts. If none of the $k$ candidates is accepted, it either abstains or falls back to the top candidate with an "unverified" flag. With the fallback, coverage stays at 100% in the SPADE sense. The verified set is the subset for which we claim higher precision.

We will write grammars for CORD receipts, FUNSD forms and XFUND forms. For FUNSD and XFUND the constraints are weaker: every answer links from a question, and headers group questions. We will allow several parents per entity so that shared values do not violate the grammar. Each grammar is capped at a fixed authoring budget of a few person-hours, and that cost is reported. Our aim is to show that a small grammar over structure captures most of the benefit. We will not build a large one.

The analysis measures how much the grammar's advantage depends on constraint strength. Arithmetic receipts are the strong case and FUNSD linking is the weak case. We expect large gains on CORD and modest ones on FUNSD, and we will report both regardless of outcome.

Baselines

The naive reference point is the SPADE graph parser with plain argmax edge decoding and no post-processing. It is trained on the same data, with the same encoder and the same OCR input. This isolates what any decoding-time structure buys.

The strongest existing method on receipts is full SPADE with Tail Collision Avoidance. The paper reports 92.5% F1 on CORD with oracle OCR and 88.1% without oracle OCR, and gains of +13.4 and +31.1 F1 over serializer baselines on the warped and tilted CORD+ and CORD++ sets (Spatial Dependency Parsing for Semi-Structured Document Information Extraction). It is the strongest competitor because it is a spatial graph parser with a rule-based decoder, which is exactly the design we claim to improve. We will retrain it ourselves so that both systems see identical training data, OCR and random seeds. Our decoder is applied to the same trained parser. Beating SPADE means higher field-level F1 on CORD+ and CORD++ at full coverage, and a higher area under the precision–coverage curve.

On forms, the reference points are SERA at 65.96% F1 on FUNSD entity relation extraction (Entity Relation Extraction as Dependency Parsing in Visually Rich Documents) and LayoutXLM-Large at 0.7206 relation-extraction F1 on XFUND, with 0.6115 average F1 reported for zero-shot transfer from English (XFUND: A Benchmark Dataset for Multilingual Visually Rich Form Understanding). The XFUND zero-shot setting is our cleanest test of layout shift: the model trains on English forms and is tested on forms whose layout conventions differ by language. We will run LayoutXLM with the same checker applied to its top-$k$ relation sets. Here we count the method as successful if verified-set precision improves at matched coverage, not if full-coverage F1 rises.

For selective prediction, the key baseline is abstention on the parser's own confidence. We rank documents by the mean or minimum edge probability, optionally after temperature calibration on the development set. We then compare it with grammar acceptance at identical coverage levels.

Two ablations isolate the key ingredient. The first replaces the grammar with purely local pairwise constraints (no token in two fields, no dangling price), solved exactly over the same $k$ candidates. This tests whether compositional and arithmetic rules matter beyond the local consistency that Tail Collision Avoidance already enforces. The second is a purely geometric rule extractor written with the same authoring budget, which should show the coverage collapse under CORD++ distortion that motivates moving rules off the page.

Why not just…?

Why not just fine-tune a larger layout-aware model instead? Larger models do help. On BuDDIE, DocLLM reaches 89.97 F1 on key entity extraction against 86.49 for LayoutLMv3 (BuDDIE: A Business Document Dataset for Multi-task Information Extraction). But bigger models still give no signal about which of their outputs are wrong, and nothing in the file shows that scale removes errors that break arithmetic. Our checker sits on top of any parser, so the honest test is to apply it to the strongest parser we can train and ask whether the verified set still gains precision. If the gain vanishes once the base parser is strong, that is a real negative result and we will report it.

Why not just abstain using the model's calibrated confidence? This is the most serious alternative. A well-calibrated parser might already rank its errors as well as a grammar does. The decisive experiment compares the two directly on precision–coverage curves, on clean CORD and on CORD++. Our hypothesis is specific: confidence calibration fitted on in-distribution data degrades under layout shift, whereas grammar acceptance does not, because a receipt's arithmetic does not depend on its geometry. If confidence matches grammar acceptance on CORD++, the selective-prediction half of this proposal fails. We would then keep only the repair half, choosing a grammatical candidate from the top $k$, and report accordingly.

Why not just use constrained decoding, as GenKIE does, or prompt a language model with a schema, as INSTRUCTE does? GenKIE's constrained beam search enforces template shape and cannot express that item prices must sum to the subtotal (GenKIE: Robust Generative Multimodal Document Key Information Extraction). INSTRUCTE's rule monitor tracks traversal on clean markup, and its authors report sensitivity to attribute naming and multi-cell spans (Schema-Driven Information Extraction from Heterogeneous Tables). Zero-shot GPT-4 on scanned business documents scores 77.76 F1 on key entity extraction, well below layout-aware models (BuDDIE). Our local-constraint ablation stands in for format-level constrained decoding. As a secondary baseline, we will also apply the same grammar check to a prompted language model's outputs on OCR text, to test whether the checker transfers across base systems.

Proposed Experiments

We will train on CORD and evaluate on CORD, CORD+ and CORD++, using both oracle and real OCR. For forms we will train and test on FUNSD, and train on English and test zero-shot on the six other XFUND languages. On BuDDIE we will write a grammar for a subset of the 69 entity labels that carry format or cross-field constraints, as a check on a harder, real business-document domain. Metrics are field-level F1 at full coverage, fraction of documents verified, precision on the verified set, area under the precision–coverage curve, and document-level exact match. Each is reported with seed variance over three runs.

Two results would settle the core question. The first is whether, at matched coverage on CORD++, documents accepted by the grammar are more precise than documents accepted by calibrated confidence, and whether that gap is larger on CORD++ than on clean CORD. The second is whether the geometric-rule baseline loses coverage under distortion while the structure grammar's acceptance rate stays close to the parser's accuracy.

A secondary check addresses the authoring cost. We will measure how F1 and verified precision change as the grammar goes from format-only rules to added hierarchy to added arithmetic. This shows which kinds of rule carry the benefit and whether a few hours of rule writing is enough. If only the arithmetic rules matter, the method applies most directly to financial and transactional documents. We will state that limitation plainly rather than claim general layout robustness.