Repository navigation
[models] Add formula recognition (FormulaNet) with LaTeX export, HGNetV2 backbone and training references - #2227
Merged
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2227 +/- ##
==========================================
+ Coverage 98.16% 98.21% +0.05%
==========================================
Files 172 181 +9
Lines 11977 12578 +601
==========================================
+ Hits 11757 12354 +597
- Misses 220 224 +4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds formula recognition to docTR: a new
formulatask that reads theFormularegions found by the layout model and returns their LaTeX source. It covers the model, the OCR pipeline, every export format, the reference training scripts, the API, the demo and the docs.The implementation is written from scratch under Apache-2.0. It follows the PP-FormulaNet design (HGNetV2 encoder with a small autoregressive decoder) and copies no code, vocabulary or weights from AGPL-licensed projects such as Texo.
Model
hgnetv2_b4(new,doctr/models/classification/hgnetv2): an HGNetV2-B4 backbone written as annn.Sequentiallike the other classification models, with pretrained weights.formulanet(new,doctr/models/formula), 26.4M parameters:max_length=4096is the longest label the model is trained on;max_decode_length=2048caps the tokens generated at inference.formula_predictor/FormulaPredictor: standalone predictor, pluspredict_regions(pages, layout_regions)to read formulas straight from layout predictions.Tokenization
LATEX_TOKENS: a fixed list of 1,324 tokens, with no BPE. It holds the printable ASCII characters, the control symbols, the commands and environments supported by KaTeX, and every other token of the UniMER-1M / HME100K / UniMER-Test labels, so those datasets are fully covered.tokenize_latex/normalize_latex: split any LaTeX string into these tokens. The model predicts the tokens separated by spaces, e.g.\frac { a } { b ^ { 2 } }.encode_string,decode_sequenceandencode_sequencesnow also accept a list of tokens, not only a string of characters.VOCABS["latex"], whichLATEX_TOKENSreplaces.Pipeline and exports
ocr_predictor(detect_formulas=True), also as--detect_formulasin the CLI. It enables the layout model, masks theFormularegions out of text detection and reads them with the formula model.Formulaelement withvalue,confidence,geometryandobjectness_scorePage.formulasattribute, included inexport()/from_dict()straighten_pages+preserve_original_coords.Export formats:
render()/ text$$/ LaTeX /$$on separate lines<div class="formula">$$...$$</div>(HTML-escaped)[latexmath]passthrough blockocr_mathelement, declared inocr-capabilitiesformulaskey of each pageOther additions
FormulaMetric(doctr/utils/metrics.py) reports exact match, token edit similarity and corpus BLEU-4, all computed on LaTeX tokens.RandomPad(doctr.transforms) pads an image with its background color and keeps box and polygon targets aligned. FormulaNet uses it in training so the model reads layout crops with their margins as they are.formulais a supported task forpush_to_hf_hub/from_hub.detect_formulasin the/ocrrequest, and aformulaslist in the response.st.latexnext to their source.references/formula/):train.pywith DDP, AMP, warmup,--save-interval-epoch(as in the other training scripts) and a--max-tokensoption that splits long padded batches into gradient-accumulated chunksevaluate.py,latency.pyandbuild_vocab.pyreferences.yml, run on a toy setTraining data and KaTeX compatibility
The model is trained on UniMER-1M plus the HME100K train split (1.06M formulas). Before training, the labels were canonicalized with rewrites that keep the rendering the same:
x ^ 2→x ^ { 2 }), and aliases take one spelling (\le→\leq,\to→\rightarrow...).\eqno ( n )→\tag { $ n $ }\ensuremath { x }→x\Tilde/\Bar/\Vec... →\tilde/\bar/\vec...\hdots→\ldots,\slash→/So the model predicts equation numbers as
\tag, which renders in KaTeX-based Markdown and HTML viewers. After the rewrite, KaTeX renders 99.34% of the training labels. The rest use commands with no KaTeX equivalent (e.g.\boldmath,\upmu,\lefteqn), as documented on the model page.Benchmark
Full UniMER-Test (23,757 formulas, labels canonicalized as above), greedy decoding:
End-to-end on five arXiv papers (1706.03762, 2410.12628, 2501.02962, 2503.17213, 2512.02498):
Formularegions are read, at 0.95–0.99 confidence.\tag.Tests
torch.compile, pipeline, export, CLI, API, metric, tokenizer andRandomPadtests.tests/common833 passed; the formula, zoo, HGNetV2, transforms and metric tests oftests/pytorch162 passed; ruff is clean.