kkuroma commited on
Commit
3fac549
·
verified ·
1 Parent(s): 27a31ab

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ language:
5
+ - en
6
+ base_model: answerdotai/ModernBERT-base
7
+ pipeline_tag: fill-mask
8
+ tags:
9
+ - document-understanding
10
+ - layoutlm
11
+ - modernbert
12
+ ---
13
+
14
+ # ModernLayoutLM
15
+
16
+ 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).
17
+
18
+ ## Intended use
19
+
20
+ The model is a pre-trained checkpoint that can be fine-tuned to layout understanding tasks, like named entity recognition or document classification.
21
+
22
+ ```python
23
+ from transformers import AutoModelForMaskedLM, AutoProcessor
24
+
25
+ path = "kkuroma/ModernLayoutLM"
26
+ model = AutoModelForMaskedLM.from_pretrained(path, trust_remote_code=True)
27
+ processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
28
+
29
+ batch = processor(words=["Total", "42.00"], boxes=[[10, 10, 60, 20], [70, 10, 140, 20]], max_length=512, return_tensors="pt")
30
+ model(**batch)
31
+ ```
32
+
33
+ - `bbox` holds one `(x0, y0, x1, y1)` per word, with the origin at the top left of the page.
34
+ - Coordinates are normalized to `[0, 1000]` by the page width and height, not given in pixels.
35
+ - Every subword of a word takes the word's box, which the bundled processor handles.
36
+ - `padding` defaults to `max_length`, which without an explicit length is the model's own 8192.
37
+ - `bbox=None` skips the layout sum and the model runs as plain ModernBERT, while all-zero boxes put every word at the origin.
38
+
39
+ ## Training data
40
+
41
+ ModernLayoutLM is pretrained on about 11M pages of English business and scientific documents, each read once, in two stages.
42
+
43
+ | stage | source | pages |
44
+ |---|---|---|
45
+ | 1 | Industry Documents Library (IDL), words and boxes from Amazon Textract | 1.5M |
46
+ | 1 | PubTables-1M | 461k |
47
+ | 1 | PDFA (`pixparse/pdfa-eng-wds`) | 160k |
48
+ | 1 | DocLayNet v1.2 | 68k |
49
+ | 2 | IDL, from the shards stage 1 never read | 8.8M |
50
+
51
+ 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.
52
+
53
+ ## Training procedure
54
+
55
+ 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.
56
+
57
+ | setting | value |
58
+ |---|---|
59
+ | sequence length | 512 tokens, packed |
60
+ | masking rate | 30%, following ModernBERT |
61
+ | batch | 64 sequences per optimizer step |
62
+ | learning rate | 5e-5 for the backbone, 1e-3 for the four layout tables |
63
+ | schedule | 5% warmup, weight decay 0.01, one epoch per stage |
64
+ | precision | fp32 master weights under bf16 autocast |
65
+ | steps | 29,899 in stage 1, 115,009 in stage 2 |
66
+
67
+ | stage | data unpacking | training |
68
+ |---|---|---|
69
+ | 1 | not recorded | 10.1 hours at 52 sequences per second |
70
+ | 2 | 0.9 hours to unpack the IDL shards, 2.3 hours to tokenize and pack | 17.9 hours at 114 sequences per second |
71
+
72
+ ## Evaluation
73
+
74
+ ### FUNSD
75
+
76
+ - Source: Jaume et al. (2019), read from `nielsr/funsd-layoutlmv3`
77
+ - Released: 2019
78
+ - Size: 199 scanned forms, 149 train and 50 test
79
+ - Task: entity labeling over header, question and answer, as 7 BIO labels
80
+
81
+ ### CORD
82
+
83
+ - Source: Park et al. (2019), read from `naver-clova-ix/cord-v2`
84
+ - Released: 2019
85
+ - Size: 1,000 Indonesian receipts, 800 train, 100 validation and 100 test
86
+ - Task: receipt field labeling over 29 categories such as menu name, price and total, as 59 BIO labels
87
+
88
+ ### SROIE
89
+
90
+ - Source: the ICDAR 2019 Competition on Scanned Receipt OCR and Information Extraction (Huang et al., 2019), read from `Ssunbell/SROIE_layoutlmv2_sequence`
91
+ - Released: 2019
92
+ - Size: 973 receipts, 594 train, 32 validation and 347 test
93
+ - Task: key information extraction over company, date, address and total, as 9 BIO labels
94
+
95
+ ### Results
96
+
97
+ Each column is one model fine-tuned on identical data.
98
+
99
+ - **ModernLayoutLM**: this model, fine-tuned with boxes.
100
+ - **LayoutLMv1**: `microsoft/layoutlm-base-uncased`, fine-tuned with boxes.
101
+ - **ModernLayoutLM (no-pretrain)**: the same architecture fine-tuned with boxes straight from ModernBERT, skipping the layout pretraining.
102
+ - **ModernLayoutLM (no-bbox)**: this model fine-tuned with every box at the origin.
103
+ - **ModernBERT**: `answerdotai/ModernBERT-base` fine-tuned on text alone.
104
+
105
+ | setting | value |
106
+ |---|---|
107
+ | metric | entity F1, and field-level Hmean per ICDAR task 3 on SROIE |
108
+ | seeds | mean ± standard deviation over three seeds |
109
+ | split | FUNSD on test as it has no validation split, the rest on validation |
110
+ | learning rate | 3e-4, chosen on FUNSD test, and 5e-5 for LayoutLMv1 as in its paper |
111
+ | epochs | 30 |
112
+ | window | 1024 tokens, 512 for LayoutLMv1 as its positions cap there |
113
+ | long documents | chunks are stitched back into one document before scoring |
114
+
115
+ | dataset | ModernLayoutLM | LayoutLMv1 | ModernLayoutLM (no-pretrain) | ModernLayoutLM (no-bbox) | ModernBERT |
116
+ |---|---|---|---|---|---|
117
+ | FUNSD | 0.7565 ± 0.0037 | 0.7785 ± 0.0104 | 0.5939 ± 0.0205 | 0.3000 ± 0.0247 | 0.5884 ± 0.0082 |
118
+ | CORD | 0.9546 ± 0.0023 | 0.9685 ± 0.0037 | 0.9462 ± 0.0050 | 0.9312 ± 0.0042 | 0.9424 ± 0.0006 |
119
+ | SROIE | 0.9337 ± 0.0060 | 0.9223 ± 0.0199 | 0.8883 ± 0.0121 | 0.8411 ± 0.0189 | 0.8955 ± 0.0072 |
120
+
121
+ ModernLayoutLM performs comparably to LayoutLMv1, but natively supports long context.
122
+
123
+ ## Citation
124
+
125
+ 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
126
+
127
+ 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. *arXiv preprint arXiv:2412.13663*. https://arxiv.org/abs/2412.13663
128
+
129
+ ```bibtex
130
+ @inproceedings{xu2020layoutlm,
131
+ title={LayoutLM: Pre-training of Text and Layout for Document Image Understanding},
132
+ author={Xu, Yiheng and Li, Minghao and Cui, Lei and Huang, Shaohan and Wei, Furu and Zhou, Ming},
133
+ booktitle={Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery \& Data Mining},
134
+ pages={1192--1200},
135
+ year={2020},
136
+ publisher={ACM},
137
+ doi={10.1145/3394486.3403172}
138
+ }
139
+
140
+ @misc{warner2024smarterbetterfasterlonger,
141
+ title={Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast, Memory Efficient, and Long Context Finetuning and Inference},
142
+ 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},
143
+ year={2024},
144
+ eprint={2412.13663},
145
+ archivePrefix={arXiv},
146
+ primaryClass={cs.CL},
147
+ url={https://arxiv.org/abs/2412.13663}
148
+ }
149
+ ```
150
+
151
+ ## License
152
+
153
+ Apache 2.0, the license ModernBERT is released under, see `LICENSE`.
config.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernLayoutLmForMaskedLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_modernlayoutlm.ModernLayoutLmConfig",
9
+ "AutoModel": "modeling_modernlayoutlm.ModernLayoutLmModel",
10
+ "AutoModelForMaskedLM": "modeling_modernlayoutlm.ModernLayoutLmForMaskedLM",
11
+ "AutoModelForSequenceClassification": "modeling_modernlayoutlm.ModernLayoutLmForSequenceClassification",
12
+ "AutoModelForTokenClassification": "modeling_modernlayoutlm.ModernLayoutLmForTokenClassification"
13
+ },
14
+ "bos_token_id": 50281,
15
+ "classifier_activation": "gelu",
16
+ "classifier_bias": false,
17
+ "classifier_dropout": 0.0,
18
+ "classifier_pooling": "mean",
19
+ "cls_token_id": 50281,
20
+ "coordinate_scale": 1000,
21
+ "decoder_bias": true,
22
+ "deterministic_flash_attn": false,
23
+ "dtype": "float32",
24
+ "embedding_dropout": 0.0,
25
+ "eos_token_id": 50282,
26
+ "global_attn_every_n_layers": 3,
27
+ "gradient_checkpointing": false,
28
+ "hidden_activation": "gelu",
29
+ "hidden_size": 768,
30
+ "initializer_cutoff_factor": 2.0,
31
+ "initializer_range": 0.02,
32
+ "intermediate_size": 1152,
33
+ "layer_norm_eps": 1e-05,
34
+ "layer_types": [
35
+ "full_attention",
36
+ "sliding_attention",
37
+ "sliding_attention",
38
+ "full_attention",
39
+ "sliding_attention",
40
+ "sliding_attention",
41
+ "full_attention",
42
+ "sliding_attention",
43
+ "sliding_attention",
44
+ "full_attention",
45
+ "sliding_attention",
46
+ "sliding_attention",
47
+ "full_attention",
48
+ "sliding_attention",
49
+ "sliding_attention",
50
+ "full_attention",
51
+ "sliding_attention",
52
+ "sliding_attention",
53
+ "full_attention",
54
+ "sliding_attention",
55
+ "sliding_attention",
56
+ "full_attention"
57
+ ],
58
+ "local_attention": 128,
59
+ "max_2d_position_embeddings": 1024,
60
+ "max_position_embeddings": 8192,
61
+ "mlp_bias": false,
62
+ "mlp_dropout": 0.0,
63
+ "model_type": "modernlayoutlm",
64
+ "norm_bias": false,
65
+ "norm_eps": 1e-05,
66
+ "num_attention_heads": 12,
67
+ "num_hidden_layers": 22,
68
+ "pad_token_id": 50283,
69
+ "position_embedding_type": "absolute",
70
+ "rope_parameters": {
71
+ "full_attention": {
72
+ "rope_theta": 160000.0,
73
+ "rope_type": "default"
74
+ },
75
+ "sliding_attention": {
76
+ "rope_theta": 10000.0,
77
+ "rope_type": "default"
78
+ }
79
+ },
80
+ "sep_token_id": 50282,
81
+ "sparse_pred_ignore_index": -100,
82
+ "sparse_prediction": false,
83
+ "tie_word_embeddings": true,
84
+ "transformers_version": "5.14.1",
85
+ "vocab_size": 50368,
86
+ "zero_init_2d": true
87
+ }
configuration_modernlayoutlm.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration for ModernLayoutLM
3
+
4
+ Extends ModernBertConfig with a coordinate vocabulary size and inherits the backbone untouched
5
+ This module is copied into exported model directories and may import only from transformers
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from transformers.models.modernbert.configuration_modernbert import ModernBertConfig
13
+
14
+ # Size to COORDINATE_SCALE + 1 rows minimum, 1024 matches LayoutLM
15
+ DEFAULT_MAX_2D_POSITION_EMBEDDINGS = 1024
16
+ DEFAULT_COORDINATE_SCALE = 1000
17
+
18
+
19
+ class ModernLayoutLmConfig(ModernBertConfig):
20
+ """
21
+ Configuration for a ModernLayoutLM model
22
+
23
+ Args:
24
+ max_2d_position_embeddings: Rows per 2D table, which lookups clamp coordinates into.
25
+ coordinate_scale: The scale boxes are normalized to, kept here so the processor agrees.
26
+ zero_init_2d: Zero the layout tables, so a fresh graft matches its backbone exactly.
27
+ **kwargs: Forwarded to `ModernBertConfig`.
28
+ """
29
+
30
+ model_type = "modernlayoutlm"
31
+
32
+ def __init__(
33
+ self,
34
+ max_2d_position_embeddings: int = DEFAULT_MAX_2D_POSITION_EMBEDDINGS,
35
+ coordinate_scale: int = DEFAULT_COORDINATE_SCALE,
36
+ zero_init_2d: bool = True,
37
+ **kwargs: Any,
38
+ ) -> None:
39
+ # Set on the class as an instance "model_type" breaks Auto dispatch
40
+ kwargs.pop("model_type", None)
41
+ super().__init__(**kwargs)
42
+ if coordinate_scale >= max_2d_position_embeddings:
43
+ raise ValueError(
44
+ f"coordinate_scale {coordinate_scale} needs "
45
+ f"max_2d_position_embeddings > {coordinate_scale}, "
46
+ f"got {max_2d_position_embeddings}"
47
+ )
48
+ self.max_2d_position_embeddings = max_2d_position_embeddings
49
+ self.coordinate_scale = coordinate_scale
50
+ self.zero_init_2d = zero_init_2d
51
+
52
+
53
+ __all__ = ["ModernLayoutLmConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3934cf273741df0fae5d60e68093386c24b254c2e1bfd3c7acf2cc3ace4937b8
3
+ size 611218424
modeling_modernlayoutlm.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ModernLayoutLM: LayoutLM's 2D layout embeddings summed into a ModernBERT backbone
3
+
4
+ The graft is confined to the embedding module so attention keeps its fused kernels and RoPE
5
+ This module is copied into exported model directories and may import only torch and transformers
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, cast
11
+
12
+ import torch
13
+ from torch import nn
14
+ from transformers.masking_utils import (
15
+ create_bidirectional_mask,
16
+ create_bidirectional_sliding_window_mask,
17
+ )
18
+ from transformers.modeling_outputs import (
19
+ BaseModelOutput,
20
+ MaskedLMOutput,
21
+ SequenceClassifierOutput,
22
+ TokenClassifierOutput,
23
+ )
24
+ from transformers.models.modernbert.modeling_modernbert import (
25
+ ModernBertEmbeddings,
26
+ ModernBertEncoderLayer,
27
+ ModernBertForMaskedLM,
28
+ ModernBertForSequenceClassification,
29
+ ModernBertForTokenClassification,
30
+ ModernBertModel,
31
+ ModernBertPreTrainedModel,
32
+ )
33
+ from transformers.utils.auto_docstring import auto_docstring
34
+ from transformers.utils.generic import merge_with_config_defaults
35
+ from transformers.utils.output_capturing import capture_outputs
36
+
37
+ from .configuration_modernlayoutlm import ModernLayoutLmConfig
38
+
39
+ # Bounding boxes arrive as (x0, y0, x1, y1) with the origin at the top left corner
40
+ BBOX_COORDS = 4
41
+
42
+
43
+ class LayoutEmbedding(nn.Embedding):
44
+ """
45
+ A coordinate embedding table, marked by its type so weight init can find it
46
+
47
+ `_init_weights` sees leaf modules, where a plain `nn.Embedding` would pass for the token table.
48
+ It would then take ModernBERT's default normal init instead of being zeroed.
49
+ """
50
+
51
+
52
+ class ModernLayoutLmEmbeddings(ModernBertEmbeddings):
53
+ """
54
+ ModernBERT's embeddings plus LayoutLM's four 2D position embedding tables
55
+
56
+ Args:
57
+ config: The model config, supplying `max_2d_position_embeddings` and `zero_init_2d`.
58
+ """
59
+
60
+ def __init__(self, config: ModernLayoutLmConfig) -> None:
61
+ super().__init__(config)
62
+ max_2d = config.max_2d_position_embeddings
63
+ self.x_position_embeddings = LayoutEmbedding(max_2d, config.hidden_size)
64
+ self.y_position_embeddings = LayoutEmbedding(max_2d, config.hidden_size)
65
+ self.w_position_embeddings = LayoutEmbedding(max_2d, config.hidden_size)
66
+ self.h_position_embeddings = LayoutEmbedding(max_2d, config.hidden_size)
67
+ if getattr(config, "zero_init_2d", True):
68
+ self.reset_layout_parameters()
69
+
70
+ def reset_layout_parameters(self) -> None:
71
+ """
72
+ Zeroes the four layout tables so the model reduces exactly to its ModernBERT backbone
73
+ """
74
+ for table in self.layout_tables():
75
+ nn.init.zeros_(table.weight)
76
+
77
+ def layout_tables(self) -> list[LayoutEmbedding]:
78
+ """
79
+ Returns the four 2D position embedding tables
80
+
81
+ Used by the optimizer to give the freshly grafted parameters their own learning rate.
82
+
83
+ Returns:
84
+ The x, y, w and h embedding tables, in that order.
85
+ """
86
+ return [
87
+ self.x_position_embeddings,
88
+ self.y_position_embeddings,
89
+ self.w_position_embeddings,
90
+ self.h_position_embeddings,
91
+ ]
92
+
93
+ def layout_embeddings(self, bbox: torch.Tensor) -> torch.Tensor:
94
+ """
95
+ Looks up and sums the six layout embeddings for each box
96
+
97
+ Coordinates clamp into the table, and a negative width or height clamps to zero.
98
+ A malformed box therefore degrades rather than raising.
99
+ `x0` and `x1` share the X table and `y0` and `y1` the Y table, matching LayoutLM v1.
100
+
101
+ Args:
102
+ bbox: Long tensor of shape (batch, seq_len, 4) holding (x0, y0, x1, y1).
103
+
104
+ Returns:
105
+ A tensor of shape (batch, seq_len, hidden_size).
106
+
107
+ Raises:
108
+ ValueError: If the last dimension of `bbox` is not 4.
109
+ """
110
+ if bbox.shape[-1] != BBOX_COORDS:
111
+ raise ValueError(f"bbox must have last dimension {BBOX_COORDS}, got {bbox.shape[-1]}")
112
+
113
+ limit = self.x_position_embeddings.num_embeddings - 1
114
+ boxes = bbox.long().clamp(0, limit)
115
+ x0, y0, x1, y1 = boxes.unbind(dim=-1)
116
+ width = (x1 - x0).clamp(0, limit)
117
+ height = (y1 - y0).clamp(0, limit)
118
+
119
+ return (
120
+ self.x_position_embeddings(x0)
121
+ + self.y_position_embeddings(y0)
122
+ + self.x_position_embeddings(x1)
123
+ + self.y_position_embeddings(y1)
124
+ + self.w_position_embeddings(width)
125
+ + self.h_position_embeddings(height)
126
+ )
127
+
128
+ def forward(
129
+ self,
130
+ input_ids: torch.LongTensor | None = None,
131
+ inputs_embeds: torch.Tensor | None = None,
132
+ bbox: torch.Tensor | None = None,
133
+ ) -> torch.Tensor:
134
+ """
135
+ Sums token and layout embeddings, then applies the inherited LayerNorm and dropout
136
+
137
+ Args:
138
+ input_ids: Token ids of shape (batch, seq_len).
139
+ bbox: Boxes of shape (batch, seq_len, 4), or None to behave as plain ModernBERT.
140
+ inputs_embeds: Precomputed token embeddings, used instead of `input_ids`.
141
+
142
+ Returns:
143
+ Normalized embeddings of shape (batch, seq_len, hidden_size).
144
+ """
145
+ if inputs_embeds is not None:
146
+ hidden_states = inputs_embeds
147
+ else:
148
+ hidden_states = self.tok_embeddings(input_ids)
149
+ if bbox is not None:
150
+ hidden_states = hidden_states + self.layout_embeddings(bbox)
151
+ return self.drop(self.norm(hidden_states))
152
+
153
+
154
+ class ModernLayoutLmPreTrainedModel(ModernBertPreTrainedModel):
155
+ """
156
+ Shared base class, extending ModernBERT's weight initialization to the layout tables
157
+ """
158
+
159
+ config_class = ModernLayoutLmConfig
160
+ base_model_prefix = "model"
161
+ _no_split_modules = ["ModernLayoutLmEmbeddings", "ModernBertEncoderLayer"]
162
+
163
+ @torch.no_grad()
164
+ def _init_weights(self, module: nn.Module) -> None:
165
+ """
166
+ Initializes a module, adding layout table handling on top of ModernBERT's rules
167
+
168
+ ModernBERT's default init is far too large to add onto a pretrained token embedding.
169
+ `from_pretrained` calls this for keys a checkpoint lacks, so a graft starts zeroed.
170
+
171
+ Args:
172
+ module: The module to initialize.
173
+ """
174
+ super()._init_weights(module)
175
+ if isinstance(module, LayoutEmbedding):
176
+ if getattr(self.config, "zero_init_2d", True):
177
+ nn.init.zeros_(module.weight)
178
+ else:
179
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
180
+
181
+
182
+ @auto_docstring
183
+ class ModernLayoutLmModel(ModernLayoutLmPreTrainedModel, ModernBertModel):
184
+ """
185
+ The bare ModernLayoutLM encoder
186
+
187
+ Identical to `ModernBertModel` except that `bbox` is threaded into the embedding module.
188
+ """
189
+
190
+ def __init__(self, config: ModernLayoutLmConfig) -> None:
191
+ super().__init__(config)
192
+ self.embeddings = ModernLayoutLmEmbeddings(config)
193
+ self.post_init()
194
+
195
+ @merge_with_config_defaults
196
+ @capture_outputs
197
+ @auto_docstring
198
+ def forward(
199
+ self,
200
+ input_ids: torch.LongTensor | None = None,
201
+ attention_mask: torch.Tensor | None = None,
202
+ position_ids: torch.Tensor | None = None,
203
+ inputs_embeds: torch.Tensor | None = None,
204
+ bbox: torch.Tensor | None = None,
205
+ **kwargs: Any,
206
+ ) -> BaseModelOutput:
207
+ r"""
208
+ bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
209
+ Boxes as (x0, y0, x1, y1) on `[0, config.coordinate_scale]`, origin at the top left.
210
+ Omitting it makes the model behave as plain ModernBERT.
211
+ """
212
+ # Branched rather than written as an xor so that the non-None case is provable
213
+ if inputs_embeds is not None:
214
+ if input_ids is not None:
215
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
216
+ seq_len, device = inputs_embeds.shape[1], inputs_embeds.device
217
+ elif input_ids is not None:
218
+ seq_len, device = input_ids.shape[1], input_ids.device
219
+ else:
220
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
221
+
222
+ if position_ids is None:
223
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0)
224
+
225
+ hidden_states = self.embeddings(
226
+ input_ids=input_ids,
227
+ bbox=bbox,
228
+ inputs_embeds=inputs_embeds,
229
+ )
230
+
231
+ if not isinstance(attention_mask_mapping := attention_mask, dict):
232
+ mask_kwargs = {
233
+ "config": self.config,
234
+ "inputs_embeds": hidden_states,
235
+ "attention_mask": attention_mask,
236
+ }
237
+ attention_mask_mapping = {
238
+ "full_attention": create_bidirectional_mask(**mask_kwargs),
239
+ "sliding_attention": create_bidirectional_sliding_window_mask(**mask_kwargs),
240
+ }
241
+
242
+ layer_types: list[str] = self.config.layer_types or []
243
+ position_embeddings = {}
244
+ for layer_type in set(layer_types):
245
+ position_embeddings[layer_type] = self.rotary_emb(
246
+ hidden_states, position_ids, layer_type
247
+ )
248
+
249
+ # Cast because nn.Module.__getattr__ erases the element type of self.layers
250
+ for module in self.layers:
251
+ encoder_layer = cast(ModernBertEncoderLayer, module)
252
+ attention_type = encoder_layer.attention_type
253
+ hidden_states = encoder_layer(
254
+ hidden_states,
255
+ attention_mask=attention_mask_mapping[attention_type],
256
+ position_embeddings=position_embeddings[attention_type],
257
+ **kwargs,
258
+ )
259
+
260
+ hidden_states = self.final_norm(hidden_states)
261
+
262
+ return BaseModelOutput(last_hidden_state=hidden_states)
263
+
264
+
265
+ @auto_docstring
266
+ class ModernLayoutLmForMaskedLM(ModernLayoutLmPreTrainedModel, ModernBertForMaskedLM):
267
+ """
268
+ ModernLayoutLM with a masked language modeling head, for the layout-aware MLM stage
269
+ """
270
+
271
+ _tied_weights_keys = {"decoder.weight": "model.embeddings.tok_embeddings.weight"}
272
+
273
+ def __init__(self, config: ModernLayoutLmConfig) -> None:
274
+ super().__init__(config)
275
+ self.model = ModernLayoutLmModel(config)
276
+ self.post_init()
277
+
278
+ def forward(
279
+ self,
280
+ input_ids: torch.LongTensor | None = None,
281
+ attention_mask: torch.Tensor | None = None,
282
+ position_ids: torch.Tensor | None = None,
283
+ inputs_embeds: torch.Tensor | None = None,
284
+ labels: torch.Tensor | None = None,
285
+ bbox: torch.Tensor | None = None,
286
+ **kwargs: Any,
287
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
288
+ """
289
+ Runs the encoder and the MLM head
290
+
291
+ `bbox` is named rather than left to `**kwargs`, as `Trainer` prunes columns by signature.
292
+ Were it implicit, the boxes would be dropped before they ever reached the model.
293
+
294
+ Args:
295
+ input_ids: Token ids of shape (batch, seq_len).
296
+ attention_mask: Mask of shape (batch, seq_len).
297
+ bbox: Boxes of shape (batch, seq_len, 4), normalized to the coordinate scale.
298
+ position_ids: Optional explicit 1D positions.
299
+ inputs_embeds: Precomputed token embeddings, used instead of `input_ids`.
300
+ labels: MLM targets of shape (batch, seq_len), `-100` where unmasked.
301
+ **kwargs: Forwarded to the backbone.
302
+
303
+ Returns:
304
+ A MaskedLMOutput, or a tuple when the config asks for one.
305
+ """
306
+ return super().forward(
307
+ input_ids=input_ids,
308
+ attention_mask=attention_mask,
309
+ position_ids=position_ids,
310
+ inputs_embeds=inputs_embeds,
311
+ labels=labels,
312
+ # Ignore as the ModernBert head forwards bbox opaquely and pyright loses it
313
+ bbox=bbox, # pyright: ignore[reportCallIssue]
314
+ **kwargs,
315
+ )
316
+
317
+
318
+ @auto_docstring
319
+ class ModernLayoutLmForTokenClassification(
320
+ ModernLayoutLmPreTrainedModel, ModernBertForTokenClassification
321
+ ):
322
+ """
323
+ ModernLayoutLM with a token classification head, for form and receipt entity extraction
324
+ """
325
+
326
+ def __init__(self, config: ModernLayoutLmConfig) -> None:
327
+ super().__init__(config)
328
+ self.model = ModernLayoutLmModel(config)
329
+ self.post_init()
330
+
331
+ def forward(
332
+ self,
333
+ input_ids: torch.LongTensor | None = None,
334
+ attention_mask: torch.Tensor | None = None,
335
+ position_ids: torch.Tensor | None = None,
336
+ inputs_embeds: torch.Tensor | None = None,
337
+ labels: torch.Tensor | None = None,
338
+ bbox: torch.Tensor | None = None,
339
+ **kwargs: Any,
340
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
341
+ """
342
+ Runs the encoder and the per-token classifier
343
+
344
+ Args:
345
+ input_ids: Token ids of shape (batch, seq_len).
346
+ attention_mask: Mask of shape (batch, seq_len).
347
+ bbox: Boxes of shape (batch, seq_len, 4), normalized to the coordinate scale.
348
+ position_ids: Optional explicit 1D positions.
349
+ inputs_embeds: Precomputed token embeddings, used instead of `input_ids`.
350
+ labels: Class index per token, `-100` to ignore.
351
+ **kwargs: Forwarded to the backbone.
352
+
353
+ Returns:
354
+ A TokenClassifierOutput, or a tuple when the config asks for one.
355
+ """
356
+ return super().forward(
357
+ input_ids=input_ids,
358
+ attention_mask=attention_mask,
359
+ position_ids=position_ids,
360
+ inputs_embeds=inputs_embeds,
361
+ labels=labels,
362
+ # Ignore as the ModernBert head forwards bbox opaquely and pyright loses it
363
+ bbox=bbox, # pyright: ignore[reportCallIssue]
364
+ **kwargs,
365
+ )
366
+
367
+
368
+ @auto_docstring
369
+ class ModernLayoutLmForSequenceClassification(
370
+ ModernLayoutLmPreTrainedModel, ModernBertForSequenceClassification
371
+ ):
372
+ """
373
+ ModernLayoutLM with a pooled sequence classification head, for document classification
374
+ """
375
+
376
+ def __init__(self, config: ModernLayoutLmConfig) -> None:
377
+ super().__init__(config)
378
+ self.model = ModernLayoutLmModel(config)
379
+ self.post_init()
380
+
381
+ def forward(
382
+ self,
383
+ input_ids: torch.LongTensor | None = None,
384
+ attention_mask: torch.Tensor | None = None,
385
+ position_ids: torch.Tensor | None = None,
386
+ inputs_embeds: torch.Tensor | None = None,
387
+ labels: torch.Tensor | None = None,
388
+ bbox: torch.Tensor | None = None,
389
+ **kwargs: Any,
390
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
391
+ """
392
+ Runs the encoder, pools per the config, then classifies the document
393
+
394
+ Args:
395
+ input_ids: Token ids of shape (batch, seq_len).
396
+ attention_mask: Mask of shape (batch, seq_len).
397
+ bbox: Boxes of shape (batch, seq_len, 4), normalized to the coordinate scale.
398
+ position_ids: Optional explicit 1D positions.
399
+ inputs_embeds: Precomputed token embeddings, used instead of `input_ids`.
400
+ labels: One class index per document.
401
+ **kwargs: Forwarded to the backbone.
402
+
403
+ Returns:
404
+ A SequenceClassifierOutput, or a tuple when the config asks for one.
405
+ """
406
+ return super().forward(
407
+ input_ids=input_ids,
408
+ attention_mask=attention_mask,
409
+ position_ids=position_ids,
410
+ inputs_embeds=inputs_embeds,
411
+ labels=labels,
412
+ # Ignore as the ModernBert head forwards bbox opaquely and pyright loses it
413
+ bbox=bbox, # pyright: ignore[reportCallIssue]
414
+ **kwargs,
415
+ )
416
+
417
+
418
+ __all__ = [
419
+ "ModernLayoutLmEmbeddings",
420
+ "ModernLayoutLmForMaskedLM",
421
+ "ModernLayoutLmForSequenceClassification",
422
+ "ModernLayoutLmForTokenClassification",
423
+ "ModernLayoutLmModel",
424
+ "ModernLayoutLmPreTrainedModel",
425
+ ]
processing_modernlayoutlm.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Turning words and boxes into model inputs
3
+
4
+ There is no image tower, so this only tokenizes words and broadcasts each box across its subwords
5
+ This module is copied into exported model directories and may import only torch and transformers
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from transformers.processing_utils import ProcessorMixin
13
+ from transformers.tokenization_utils_base import BatchEncoding
14
+
15
+ # Follow LayoutLM: CLS at the origin, SEP at the far corner, padding masked out
16
+ CLS_BOX = (0, 0, 0, 0)
17
+ SEP_BOX = (1000, 1000, 1000, 1000)
18
+ PAD_BOX = (0, 0, 0, 0)
19
+
20
+ # Label id meaning "do not compute loss here", the torch cross-entropy default
21
+ IGNORE_INDEX = -100
22
+
23
+
24
+ class ModernLayoutLmProcessor(ProcessorMixin):
25
+ """
26
+ Pairs a fast tokenizer with box and label expansion over subwords
27
+
28
+ Args:
29
+ tokenizer: Any fast tokenizer, so the LayoutLM baseline reuses this with its own one.
30
+ coordinate_scale: The scale boxes are expected to already be normalized to.
31
+ label_all_subwords: Label every subword, not only the first as published FUNSD and CORD do.
32
+ """
33
+
34
+ attributes = ["tokenizer"]
35
+ tokenizer_class = "AutoTokenizer"
36
+
37
+ def __init__(
38
+ self,
39
+ tokenizer: Any,
40
+ coordinate_scale: int = 1000,
41
+ label_all_subwords: bool = False,
42
+ ) -> None:
43
+ self.coordinate_scale = coordinate_scale
44
+ self.label_all_subwords = label_all_subwords
45
+ super().__init__(tokenizer)
46
+
47
+ # Diverge as ProcessorMixin.__call__ is typed for image and audio processors
48
+ def __call__( # pyright: ignore[reportIncompatibleMethodOverride]
49
+ self,
50
+ words: list[str] | list[list[str]],
51
+ boxes: list[list[int]] | list[list[list[int]]],
52
+ word_labels: list[int] | list[list[int]] | None = None,
53
+ max_length: int | None = None,
54
+ padding: bool | str = "max_length",
55
+ truncation: bool = True,
56
+ return_overflowing_tokens: bool = False,
57
+ stride: int = 0,
58
+ return_tensors: str | None = None,
59
+ **kwargs: Any,
60
+ ) -> BatchEncoding:
61
+ """
62
+ Tokenizes words and aligns boxes, and optionally labels, to the resulting subwords
63
+
64
+ Accepts one document or a batch, told apart by whether `words` holds strings or lists.
65
+ Special tokens receive the sentinel boxes defined in this module.
66
+ With `return_overflowing_tokens` a long page becomes several chunks, each with its boxes.
67
+
68
+ Args:
69
+ words: One document's words, or a batch of documents' words.
70
+ boxes: One (x0, y0, x1, y1) box per word on `coordinate_scale`, batched like `words`.
71
+ word_labels: One class index per word, batched like `words`, or None for no labels.
72
+ max_length: Truncation length, by default the tokenizer's own.
73
+ padding: Passed to the tokenizer.
74
+ truncation: Passed to the tokenizer.
75
+ return_overflowing_tokens: Emit every chunk of an over-length page, not only the first.
76
+ stride: Overlap in tokens between consecutive chunks.
77
+ return_tensors: "pt" for torch tensors, None for lists.
78
+ **kwargs: Forwarded to the tokenizer.
79
+
80
+ Returns:
81
+ A BatchEncoding of `input_ids`, `attention_mask`, `bbox`, plus `labels` if given any.
82
+
83
+ Raises:
84
+ ValueError: If `words` and `boxes` differ in length, or a coordinate leaves the grid.
85
+ """
86
+ batched = bool(words) and isinstance(words[0], list)
87
+ batch_words: list[list[str]] = words if batched else [words] # type: ignore[assignment]
88
+ batch_boxes: list[list[list[int]]] = boxes if batched else [boxes] # type: ignore[assignment]
89
+ batch_labels: list[list[int]] | None = None
90
+ if word_labels is not None:
91
+ batch_labels = word_labels if batched else [word_labels] # type: ignore[assignment]
92
+
93
+ self._validate(batch_words, batch_boxes, batch_labels)
94
+
95
+ encoding = self.tokenizer(
96
+ text=batch_words,
97
+ is_split_into_words=True,
98
+ max_length=max_length,
99
+ padding=padding,
100
+ truncation=truncation,
101
+ return_overflowing_tokens=return_overflowing_tokens,
102
+ stride=stride,
103
+ return_tensors=None,
104
+ **kwargs,
105
+ )
106
+
107
+ sample_map = encoding.get("overflow_to_sample_mapping")
108
+ if sample_map is None:
109
+ sample_map = list(range(len(encoding["input_ids"])))
110
+
111
+ aligned_boxes: list[list[list[int]]] = []
112
+ aligned_labels: list[list[int]] = []
113
+ for chunk_index, sample_index in enumerate(sample_map):
114
+ word_ids = encoding.word_ids(chunk_index)
115
+ source_boxes = batch_boxes[sample_index]
116
+ aligned_boxes.append(self._expand_boxes(word_ids, source_boxes))
117
+ if batch_labels is not None:
118
+ aligned_labels.append(self._expand_labels(word_ids, batch_labels[sample_index]))
119
+
120
+ encoding["bbox"] = aligned_boxes
121
+ if batch_labels is not None:
122
+ encoding["labels"] = aligned_labels
123
+
124
+ if return_tensors is not None:
125
+ encoding.convert_to_tensors(tensor_type=return_tensors)
126
+ return encoding
127
+
128
+ def _validate(
129
+ self,
130
+ batch_words: list[list[str]],
131
+ batch_boxes: list[list[list[int]]],
132
+ batch_labels: list[list[int]] | None,
133
+ ) -> None:
134
+ """
135
+ Checks that the parallel inputs line up and the coordinates are in range
136
+
137
+ A misalignment would otherwise train a model on wrong boxes without ever erroring.
138
+
139
+ Args:
140
+ batch_words: Words per document.
141
+ batch_boxes: Boxes per document.
142
+ batch_labels: Labels per document, or None.
143
+
144
+ Raises:
145
+ ValueError: On a length mismatch or an out of range coordinate.
146
+ """
147
+ if len(batch_words) != len(batch_boxes):
148
+ raise ValueError(f"Got {len(batch_words)} word lists but {len(batch_boxes)} box lists")
149
+ if batch_labels is not None and len(batch_labels) != len(batch_words):
150
+ raise ValueError(
151
+ f"Got {len(batch_words)} word lists but {len(batch_labels)} label lists"
152
+ )
153
+
154
+ for index, (doc_words, doc_boxes) in enumerate(zip(batch_words, batch_boxes, strict=True)):
155
+ if len(doc_words) != len(doc_boxes):
156
+ raise ValueError(
157
+ f"Document {index} has {len(doc_words)} words but {len(doc_boxes)} boxes"
158
+ )
159
+ if batch_labels is not None and len(batch_labels[index]) != len(doc_words):
160
+ raise ValueError(
161
+ f"Document {index} has {len(doc_words)} words "
162
+ f"but {len(batch_labels[index])} labels"
163
+ )
164
+ for box in doc_boxes:
165
+ if len(box) != 4:
166
+ raise ValueError(f"Document {index} has a box with {len(box)} coordinates")
167
+ if any(not 0 <= value <= self.coordinate_scale for value in box):
168
+ raise ValueError(
169
+ f"Document {index} has box {box} outside "
170
+ f"[0, {self.coordinate_scale}]. Normalize before calling the processor."
171
+ )
172
+
173
+ def _expand_boxes(
174
+ self,
175
+ word_ids: list[int | None],
176
+ source_boxes: list[list[int]],
177
+ ) -> list[list[int]]:
178
+ """
179
+ Assigns a box to every token position in one chunk
180
+
181
+ Args:
182
+ word_ids: Per-token index into `source_boxes`, None for special and padding tokens.
183
+ source_boxes: One box per word of the source document.
184
+
185
+ Returns:
186
+ One box per token position.
187
+ """
188
+ special_boxes = self._special_boxes(word_ids)
189
+ return [
190
+ list(source_boxes[word_id]) if word_id is not None else special_boxes[position]
191
+ for position, word_id in enumerate(word_ids)
192
+ ]
193
+
194
+ def _special_boxes(self, word_ids: list[int | None]) -> dict[int, list[int]]:
195
+ """
196
+ Chooses a sentinel box for each token that came from no word
197
+
198
+ Leading specials sit at the origin like CLS, and the first trailing one at the far corner.
199
+ Everything past it is padding at the origin.
200
+
201
+ Args:
202
+ word_ids: Per-token index into the source words, None for non-word tokens.
203
+
204
+ Returns:
205
+ A mapping from token position to sentinel box.
206
+ """
207
+ word_positions = [i for i, word_id in enumerate(word_ids) if word_id is not None]
208
+ last_word = word_positions[-1] if word_positions else -1
209
+
210
+ boxes: dict[int, list[int]] = {}
211
+ seen_separator = False
212
+ for position, word_id in enumerate(word_ids):
213
+ if word_id is not None:
214
+ continue
215
+ if position < last_word:
216
+ boxes[position] = list(CLS_BOX)
217
+ elif not seen_separator:
218
+ boxes[position] = list(SEP_BOX)
219
+ seen_separator = True
220
+ else:
221
+ boxes[position] = list(PAD_BOX)
222
+ return boxes
223
+
224
+ def _expand_labels(
225
+ self,
226
+ word_ids: list[int | None],
227
+ source_labels: list[int],
228
+ ) -> list[int]:
229
+ """
230
+ Assigns a label to every token position in one chunk
231
+
232
+ Special and padding tokens always get `IGNORE_INDEX`.
233
+ Whether the later subwords of a word inherit its label follows `label_all_subwords`.
234
+
235
+ Args:
236
+ word_ids: Per-token index into `source_labels`, None for non-word tokens.
237
+ source_labels: One class index per word of the source document.
238
+
239
+ Returns:
240
+ One label per token position.
241
+ """
242
+ labels: list[int] = []
243
+ previous = None
244
+ for word_id in word_ids:
245
+ if word_id is None:
246
+ labels.append(IGNORE_INDEX)
247
+ elif word_id != previous or self.label_all_subwords:
248
+ labels.append(source_labels[word_id])
249
+ else:
250
+ labels.append(IGNORE_INDEX)
251
+ previous = word_id
252
+ return labels
253
+
254
+
255
+ __all__ = ["ModernLayoutLmProcessor"]
processor_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_modernlayoutlm.ModernLayoutLmProcessor"
4
+ },
5
+ "coordinate_scale": 1000,
6
+ "label_all_subwords": false,
7
+ "processor_class": "ModernLayoutLmProcessor"
8
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_modernlayoutlm.ModernLayoutLmProcessor"
4
+ },
5
+ "backend": "tokenizers",
6
+ "clean_up_tokenization_spaces": true,
7
+ "cls_token": "[CLS]",
8
+ "is_local": true,
9
+ "local_files_only": false,
10
+ "mask_token": "[MASK]",
11
+ "model_input_names": [
12
+ "input_ids",
13
+ "attention_mask"
14
+ ],
15
+ "model_max_length": 8192,
16
+ "pad_token": "[PAD]",
17
+ "processor_class": "ModernLayoutLmProcessor",
18
+ "sep_token": "[SEP]",
19
+ "tokenizer_class": "TokenizersBackend",
20
+ "unk_token": "[UNK]"
21
+ }