/ Модель

Характеристики

Контекст
8 192 токена
Параметры
149 млн
Лицензия
Apache 2.0
Архитектура
modernlayoutlm · dense
Базовая модель
ModernBERT-base
Библиотека
transformers
Опубликована
5 окт 2026

ModernLayoutLM

Заполнение пропусковТекст → текст

Предобученный англоязычный энкодер ModernBERT с учетом расположения текста на странице для извлечения данных и классификации документов.

59скачиваний за 30 дней1лайквеса обновлены5 окт 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

ModernLayoutLM — англоязычный предобученный чекпойнт для понимания документов, созданный автором репозитория kkuroma. Модель объединяет двунаправленный энкодер ModernBERT и информацию о расположении слов на странице по подходу LayoutLMv1. Она содержит 149 млн параметров, поддерживает контекст до 8192 токенов и рассчитана на дальнейшее дообучение для извлечения полей, распознавания именованных сущностей и классификации документов.

На вход подаются текстовые слова и соответствующие им ограничивающие рамки, координаты которых нормализованы в диапазон от 0 до 1000; обработчик модели распределяет рамку слова по его подсловам. В README описаны эксперименты на формах, чеках и длинных деловых документах. Модель показывает результаты, сопоставимые с LayoutLMv1, и рассчитана на длинный контекст. Доступен режим без координат, в котором модель работает как обычный ModernBERT. Лицензия — Apache-2.0.

Сценарии применения

  • извлечение полей из счетов и договоров
  • распознавание именованных сущностей в формах
  • разметка полей в чеках
  • классификация деловых документов
  • обработка длинных OCR-документов с учетом координат текста

Ограничения

Модель предобучена преимущественно на английских деловых и научных документах, поэтому её применимость к другим языкам и типам документов не подтверждена. Для учета макета нужны корректные OCR-текст и нормализованные координаты слов; для прикладных задач модель следует дообучить.

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

ModernLayoutLM

Fine-tuned score and document length per task, for ModernLayoutLM, LayoutLMv1 and ModernBERT

ModernLayoutLM is an attempt to produce a long-context (like ModernBERT) bidirectional encoder that incorporates layout information into its training (like LayoutLM). ModernLayoutLM uses the same recipe as Xu et al. (2020) in the creation of LayoutLMv1, where the major difference is swapping BERT with ModernBERT (Warner et al., 2024).

Intended use

The model is a pre-trained checkpoint that can be fine-tuned to layout understanding tasks, like named entity recognition or document classification.

from transformers import AutoModelForMaskedLM, AutoProcessor

path = "kkuroma/ModernLayoutLM"
model = AutoModelForMaskedLM.from_pretrained(path, trust_remote_code=True)
processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)

batch = processor(words=["Total", "42.00"], boxes=[[10, 10, 60, 20], [70, 10, 140, 20]], max_length=512, return_tensors="pt")
model(**batch)
  • bbox holds one (x0, y0, x1, y1) per word, with the origin at the top left of the page.
  • Coordinates are normalized to [0, 1000] by the page width and height, not given in pixels.
  • Every subword of a word takes the word's box, which the bundled processor handles.
  • padding defaults to max_length, which without an explicit length is the model's own 8192.
  • bbox=None skips the layout sum and the model runs as plain ModernBERT, while all-zero boxes put every word at the origin.
  • Attention defaults to SDPA; attn_implementation="flash_attention_2" with flash-attn installed is faster and lighter on long documents, see Inference cost.

Training data

ModernLayoutLM is pretrained on about 11M pages of English business and scientific documents, each read once, in two stages.

stagesourcepages
1Industry Documents Library (IDL), words and boxes from Amazon Textract1.5M
1PubTables-1M461k
1PDFA (pixparse/pdfa-eng-wds)160k
1DocLayNet v1.268k
2IDL, from the shards stage 1 never read8.8M

Pages carrying a Bates number from the FUNSD or RVL-CDIP evaluation splits are dropped from both stages, since IDL and those benchmarks share IIT-CDIP.

Training procedure

ModernLayoutLM is pretrained with the masked visual-language model of LayoutLMv1 (Xu et al., 2020). Four 2D position embedding tables, where x0 and x1 share table X and y0 and y1 share table Y, are summed into the token embeddings before the embedding LayerNorm. Text is masked and boxes are left intact, so recovering a masked token rewards reading its position on the page. The four tables start at zero, so the model starts numerically identical to ModernBERT. The number of iterations and the duration are set by hardware limitations, as every step ran on a single RTX 3090.

settingvalue
sequence length512 tokens, packed
masking rate30%, following ModernBERT
batch64 sequences per optimizer step
learning rate5e-5 for the backbone, 1e-3 for the four layout tables
schedule5% warmup, weight decay 0.01, one epoch per stage
precisionfp32 master weights under bf16 autocast
steps29,899 in stage 1, 115,009 in stage 2
stagedata unpackingtraining
1not recorded10.1 hours at 52 sequences per second
20.9 hours to unpack the IDL shards, 2.3 hours to tokenize and pack17.9 hours at 114 sequences per second

Evaluation

FUNSD

  • Source: Jaume et al. (2019), read from nielsr/funsd
  • Released: 2019
  • Size: 199 scanned forms, 149 train and 50 test
  • Task: entity labeling over header, question and answer, as 7 BIO labels

CORD

  • Source: Park et al. (2019), read from naver-clova-ix/cord-v2
  • Released: 2019
  • Size: 1,000 Indonesian receipts, 800 train, 100 validation and 100 test
  • Task: receipt field labeling over 29 categories such as menu name, price and total, as 59 BIO labels

SROIE

  • Source: the ICDAR 2019 Competition on Scanned Receipt OCR and Information Extraction (Huang et al., 2019), read from Ssunbell/SROIE_layoutlmv2_sequence
  • Released: 2019
  • Size: 973 receipts, 594 train, 32 validation and 347 test
  • Task: key information extraction over company, date, address and total, as 9 BIO labels

RealKIE

  • Source: Townsend et al. (2024), the FCC Invoices, NDA and Charities sets, read from the Zenodo release with its own OCR
  • Released: 2024
  • Size: long multi-page documents, 38% to 55% of them past 4096 tokens
  • Task: key information extraction labeled as character spans over the OCR text
settrain, validation and test documentsfieldsBIO labelsmedian tokens
FCC Invoices221, 75 and 7411232,948
NDA248, 93 and 98373,522
Charities322, 108 and 10828574,525

Results

Each column is one model fine-tuned on identical data.

  • ModernLayoutLM: this model, fine-tuned with boxes.
  • LayoutLMv1: microsoft/layoutlm-base-uncased, fine-tuned with boxes.
  • ModernLayoutLM (no-pretrain): the same architecture fine-tuned with boxes straight from ModernBERT, skipping the layout pretraining.
  • ModernLayoutLM (no-bbox): this model fine-tuned with every box at the origin.
  • ModernBERT: answerdotai/ModernBERT-base fine-tuned on text alone.
settingvalue
metricentity F1, and field-level Hmean per ICDAR task 3 on SROIE
seedsmean ± standard deviation over three seeds, one seed on RealKIE
splitFUNSD on test as it has no validation split, the rest on validation
learning rate3e-4, chosen on FUNSD test, and 5e-5 for LayoutLMv1 as in its paper
epochs30, 10 on RealKIE
window1024 tokens, 4096 on RealKIE, 512 for LayoutLMv1 as its positions cap there
long documentschunks are stitched back into one document before scoring
datasetModernLayoutLMLayoutLMv1ModernLayoutLM (no-pretrain)ModernLayoutLM (no-bbox)ModernBERT
FUNSD0.7565 ± 0.00370.7785 ± 0.01040.5939 ± 0.02050.3000 ± 0.02470.5884 ± 0.0082
CORD0.9546 ± 0.00230.9685 ± 0.00370.9462 ± 0.00500.9312 ± 0.00420.9424 ± 0.0006
SROIE0.9337 ± 0.00600.9223 ± 0.01990.8883 ± 0.01210.8411 ± 0.01890.8955 ± 0.0072
RealKIE FCC0.87610.86130.85690.71780.8607
RealKIE NDA0.85860.85390.85030.57350.8571
RealKIE Charities0.80430.80710.76790.37400.7725

ModernLayoutLM performs comparably to LayoutLMv1, but natively supports long context.

Inference cost

Latency and peak GPU memory per document for ModernLayoutLM with FA2 and SDPA, and LayoutLMv1 in 512-token windows

settingvalue
inputone document per forward pass, bf16, 23-label token head
hardwareRTX 3090 capped at 270W
timingmedian of three rounds of 30 passes, the model order alternating between rounds
memorypeak allocated, weights included
LayoutLMv1512-token windows overlapping by 128, run as one batch with eager attention, its only option in transformers
tokensLayoutLMv1 windowsLayoutLMv1 msModernLayoutLM SDPA msModernLayoutLM FA2 msLayoutLMv1 GiBModernLayoutLM SDPA GiBModernLayoutLM FA2 GiB
51215.87.47.40.240.300.30
1024314.313.912.50.310.310.31
2048627.330.724.80.410.350.33
40961148.676.952.20.570.540.37
81922295.1215.7113.80.941.300.46

Citation

Xu, Y., Li, M., Cui, L., Huang, S., Wei, F., & Zhou, M. (2020). LayoutLM: Pre-training of Text and Layout for Document Image Understanding. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (pp. 1192-1200). https://doi.org/10.1145/3394486.3403172

Warner, B., Chaffin, A., Clavié, B., Weller, O., Hallström, O., Taghadouini, S., Gallagher, A., Biswas, R., Ladhak, F., Aarsen, T., Cooper, N., Adams, G., Howard, J., & Poli, I. (2024). Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast, Memory Efficient, and Long Context Finetuning and Inference. Preprint.

@inproceedings{xu2020layoutlm,
  title={LayoutLM: Pre-training of Text and Layout for Document Image Understanding},
  author={Xu, Yiheng and Li, Minghao and Cui, Lei and Huang, Shaohan and Wei, Furu and Zhou, Ming},
  booktitle={Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery \& Data Mining},
  pages={1192--1200},
  year={2020},
  publisher={ACM},
  doi={10.1145/3394486.3403172}
}

@misc{warner2024smarterbetterfasterlonger,
  title={Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast, Memory Efficient, and Long Context Finetuning and Inference},
  author={Benjamin Warner and Antoine Chaffin and Benjamin Clavi{\'e} and Orion Weller and Oskar Hallstr{\"o}m and Said Taghadouini and Alexis Gallagher and Raja Biswas and Faisal Ladhak and Tom Aarsen and Nathan Cooper and Griffin Adams and Jeremy Howard and Iacopo Poli},
  year={2024}
}

License

Apache 2.0, the license ModernBERT is released under, see LICENSE.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers · fill-mask

Нельзя запустить

Модели нужен код из репозитория; автор пока не в списке доверенных организаций.

Класс архитектуры
ModernLayoutLmForMaskedLM
Ревизия весов
f872f05

0 моделей