iamleonie mlabonne mini97 commited on
Commit
4e2f724
·
0 Parent(s):

Initial public commit

Browse files

Co-authored-by: mlabonne <mlabonne@users.noreply.huggingface.co>
Co-authored-by: mini97 <mini97@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LFM Open License v1.0
2
+
3
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4
+
5
+ 1. Definitions.
6
+
7
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
8
+
9
+ "Licensor" shall mean Liquid AI, Inc.
10
+
11
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
12
+
13
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
14
+
15
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
16
+
17
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
18
+
19
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
20
+
21
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
22
+
23
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
24
+
25
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
26
+
27
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
28
+
29
+ "Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
30
+
31
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
32
+
33
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
34
+
35
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
36
+
37
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
38
+
39
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Commercial Use Limitation.
52
+
53
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
54
+
55
+ (b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
56
+
57
+ (c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
58
+
59
+ 6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
60
+
61
+ 7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
62
+
63
+ 8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
68
+
69
+ 11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
70
+
71
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - de
5
+ - fr
6
+ - es
7
+ - it
8
+ - pt
9
+ - nl
10
+ - ru
11
+ - ja
12
+ - zh
13
+ - ko
14
+ tags:
15
+ - liquid
16
+ - lfm2
17
+ - lfm2.5
18
+ - bidirectional
19
+ - masked-lm
20
+ - encoder
21
+ - grammatical-error-correction
22
+ - gec
23
+ - spell-check
24
+ - token-classification
25
+ - gector
26
+ library_name: transformers
27
+ license: other
28
+ license_name: lfm1.0
29
+ license_link: LICENSE
30
+ pipeline_tag: token-classification
31
+ base_model:
32
+ - LiquidAI/LFM2.5-Encoder-350M
33
+ ---
34
+
35
+ <div align="center">
36
+ <img
37
+ src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
38
+ alt="Liquid AI"
39
+ style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
40
+ />
41
+ <div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;">
42
+ <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
43
+ <a href="https://docs.liquid.ai/lfm/getting-started/welcome"><strong>Docs</strong></a> •
44
+ <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> •
45
+ <a href="https://discord.com/invite/liquid-ai"><strong>Discord</strong></a>
46
+ </div>
47
+ </div>
48
+
49
+ # LFM2.5-Encoder-350-Spellchecker
50
+
51
+ A full fine-tune of [LFM2.5-Encoder-350M](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M) with a subword-level **GECToR-style grammatical-error-correction tagger**.
52
+ It covers grammar, spelling, punctuation, and casing in English.
53
+
54
+ Find more details about our encoders in our [blog post](https://www.liquid.ai/blog/lfm2-5-encoders).
55
+
56
+ > [!NOTE]
57
+ > 💻 **Demos**: Try this fine-tuned model running in a CPU-only Hugging Face space:
58
+ > **[Spell checking](https://huggingface.co/spaces/LiquidAI/spellchecker)** — correct misspellings token by token.
59
+
60
+ ## Usage
61
+
62
+ > ⚠️ Loads custom code via `trust_remote_code=True` (the model wraps a `trust_remote_code` encoder).
63
+
64
+ Install the required packages:
65
+
66
+ ```bash
67
+ pip install torch transformers
68
+ ```
69
+
70
+ Run spell checking:
71
+
72
+ ```python
73
+ from transformers import AutoModel
74
+
75
+ model_id = "LiquidAI/LFM2.5-Encoder-350-Spellchecker"
76
+
77
+ model = AutoModel.from_pretrained(
78
+ model_id,
79
+ trust_remote_code=True,
80
+ ).float().eval()
81
+
82
+ print(model.correct(["She go to school every day ."]))
83
+ # ['She goes to school every day .']
84
+ ```
85
+
86
+ `correct()` accepts a string or a list; tune precision with `min_error_prob` (higher → fewer edits) and
87
+ `max_iter` (refinement passes). Input should be whitespace-tokenized (punctuation separated by spaces),
88
+ matching the training data.
89
+
90
+ ## Evaluation
91
+
92
+ Fixed inference setting: `max_iter=4`, precision knobs off. Headline [ERRANT](https://github.com/chrisjbryant/errant) F0.5:
93
+
94
+ **MASTER composite (selection metric): 64.24**
95
+
96
+ | Benchmark | Precision | Recall | F0.5 |
97
+ |---|--:|--:|--:|
98
+ | LOCNESS native (ERRANT) | 53.77 | 34.53 | 48.38 |
99
+ | BEA-dev (ERRANT) | 56.48 | 28.96 | 47.46 |
100
+ | CoNLL-14 (ERRANT) | 67.54 | 18.91 | 44.59 |
101
+ | FCE-test (ERRANT) | 57.31 | 32.63 | 49.78 |
102
+ | Robustness (ERRANT) | 91.96 | 87.98 | 91.14 |
103
+ | Multilingual dev (F0.5) | — | — | — |
104
+
105
+ ## Examples
106
+
107
+ | Input | Correction |
108
+ |---|---|
109
+ | `She go to school every day .` | `She goes to school every day .` |
110
+ | `I has went to the stor yesterday .` | `I went to the store yesterday .` |
111
+ | `Their are many reason to study hard .` | `There are many reasons to study hard .` |
112
+ | `He don&#x27;t like coffee but he like tea .` | `He does n&#x27;t like coffee , but he likes tea .` |
113
+
114
+ ## 📬 Contact
115
+
116
+ - Got questions or want to connect? [Join our Discord community](https://discord.com/invite/liquid-ai)
117
+ - If you are interested in custom solutions with edge deployment, please contact [our sales team](https://www.liquid.ai/contact).
118
+
119
+ ## Citation
120
+
121
+ ```bibtex
122
+ @article{liquidAI2026Encoders,
123
+ author = {Liquid AI},
124
+ title = {LFM2.5-Encoders: Fast at Long Context, Even on CPU},
125
+ journal = {Liquid AI Blog},
126
+ year = {2026},
127
+ note = {www.liquid.ai/blog/lfm2-5-encoders},
128
+ }
129
+ ```
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GecTaggerForGEC"
4
+ ],
5
+ "model_type": "gec_tagger",
6
+ "auto_map": {
7
+ "AutoConfig": "modeling_gectagger.GecTaggerConfig",
8
+ "AutoModel": "modeling_gectagger.GecTaggerForGEC"
9
+ },
10
+ "encoder_name": "LiquidAI/LFM2.5-Encoder-350M",
11
+ "num_tags": 128802,
12
+ "hidden_size": 1024,
13
+ "tie_replace": true,
14
+ "multi_head": false,
15
+ "aux_loss_weight": 0.5,
16
+ "use_swap": false,
17
+ "qat_applied": false,
18
+ "qat_group_size": 32,
19
+ "dropout": 0.1,
20
+ "torch_dtype": "float16"
21
+ }
examples.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "source": "She go to school every day .",
4
+ "corrected": "She goes to school every day ."
5
+ },
6
+ {
7
+ "source": "I has went to the stor yesterday .",
8
+ "corrected": "I went to the store yesterday ."
9
+ },
10
+ {
11
+ "source": "Their are many reason to study hard .",
12
+ "corrected": "There are many reasons to study hard ."
13
+ },
14
+ {
15
+ "source": "He don't like coffee but he like tea .",
16
+ "corrected": "He does n't like coffee , but he likes tea ."
17
+ }
18
+ ]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e788053172f2dbc5a1573454475230dca21f19cd3ca1193e2dca5b1a9fd27bfa
3
+ size 713449656
modeling_gectagger.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained `transformers` modeling code for the LFM2.5 subword GEC tagger.
2
+
3
+ This file ships INSIDE the Hugging Face model repo and is loaded via `trust_remote_code=True`. It must
4
+ NOT import the `spellchecker` package (end users won't have it) — the architecture, the algorithmic
5
+ subword tag space, and the iterative decode loop are all inlined here so the published model is usable
6
+ with nothing but `transformers`:
7
+
8
+ from transformers import AutoModel
9
+ model = AutoModel.from_pretrained("LiquidAI/LFM2.5-Spellchecker-350M", trust_remote_code=True)
10
+ print(model.correct(["She go to school every day ."]))
11
+ # -> ["She goes to school every day ."]
12
+
13
+ The tagger is a GECToR-style two-head model on a bidirectional MLM encoder. Tags are predicted per BPE
14
+ piece; the label space is algorithmic (no vocab file):
15
+
16
+ 0 = $KEEP leave this piece
17
+ 1 = $DELETE drop this piece
18
+ 2 = $SWAP (only when use_swap) swap this piece with the next one
19
+ base..base+V = $REPLACE_<piece_id> replace this piece with BPE piece <piece_id>
20
+ base+V.. = $APPEND_<piece_id> keep this piece, insert BPE piece <piece_id> after it
21
+ base = 3 if use_swap else 2 ; num_labels = base + 2*V ; V = tokenizer vocab size
22
+
23
+ Multi-piece / multi-word corrections emerge over the iterative passes (`correct` re-runs the tagger
24
+ until the text stops changing or `max_iter` is hit). The sentence-initial anchor is the tokenizer BOS,
25
+ prepended to every sequence; an $APPEND on it inserts at sentence start.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ from typing import List
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ from transformers import AutoConfig, AutoModelForMaskedLM, PretrainedConfig, PreTrainedModel
34
+
35
+ # The self-contained reranker companion ships in the SAME repo (export_hub.py copies it next to this
36
+ # file). transformers' trust_remote_code resolver scans the source for a relative import and ALSO copies
37
+ # that sibling into the dynamic-module cache when the repo is loaded by id — without it the companion is
38
+ # never materialised and the lazy load below would ModuleNotFoundError. The import FORM matters: the
39
+ # resolver (dynamic_module_utils.get_relative_imports) only matches `from .<name> import ...` or
40
+ # `import .<name>` — `from . import <name>` is NOT matched. So we import a sentinel from the companion
41
+ # (which forces it into sys.modules) and grab the module object via sys.modules. Best effort: a model
42
+ # with no reranker bundled (older export) still loads tagger-only.
43
+ try:
44
+ from .reranker_gectagger import rerank as _rerank_fn # noqa: F401 (resolver hint)
45
+ import sys as _sys
46
+ _reranker_mod = _sys.modules[__name__.rsplit(".", 1)[0] + ".reranker_gectagger"] \
47
+ if "." in __name__ else _sys.modules["reranker_gectagger"]
48
+ except Exception: # standalone / no companion -> tagger-only
49
+ _reranker_mod = None
50
+
51
+ # --------------------------------------------------------------------------- tag space (algorithmic)
52
+
53
+ KEEP_ID, DELETE_ID, SWAP_ID = 0, 1, 2
54
+ INCORRECT = 1 # detection-head class id gated by min_error_prob
55
+ REPLACE, APPEND, SWAP = "$REPLACE_", "$APPEND_", "$SWAP"
56
+
57
+
58
+ def _rep_base(use_swap: bool) -> int:
59
+ return 3 if use_swap else 2
60
+
61
+
62
+ def id_to_tag(idx: int, vocab_size: int, use_swap: bool = False) -> str:
63
+ if idx == KEEP_ID:
64
+ return "$KEEP"
65
+ if idx == DELETE_ID:
66
+ return "$DELETE"
67
+ if use_swap and idx == SWAP_ID:
68
+ return SWAP
69
+ base = _rep_base(use_swap)
70
+ if idx < base + vocab_size:
71
+ return f"{REPLACE}{idx - base}"
72
+ return f"{APPEND}{idx - base - vocab_size}"
73
+
74
+
75
+ def apply_tags(pieces: List[int], tags: List[str]) -> List[int]:
76
+ """Apply per-piece tags, returning the new piece-id list. pieces[0] is the BOS anchor and is never
77
+ emitted (an $APPEND on it inserts at sentence start). $SWAP emits the next piece then this one and
78
+ consumes both; it never fires on the BOS anchor."""
79
+ out: List[int] = []
80
+ i, n = 0, len(pieces)
81
+ while i < n:
82
+ p, t = pieces[i], tags[i]
83
+ is_start = i == 0
84
+ if t == SWAP and not is_start and i + 1 < n:
85
+ out.append(pieces[i + 1]); out.append(p); i += 2; continue
86
+ if t == "$KEEP" or t == SWAP: # SWAP with no valid neighbour -> safe keep
87
+ if not is_start:
88
+ out.append(p)
89
+ elif t == "$DELETE":
90
+ pass
91
+ elif t.startswith(REPLACE):
92
+ out.append(int(t[len(REPLACE):]))
93
+ elif t.startswith(APPEND):
94
+ if not is_start:
95
+ out.append(p)
96
+ out.append(int(t[len(APPEND):]))
97
+ else: # unknown -> safe keep
98
+ if not is_start:
99
+ out.append(p)
100
+ i += 1
101
+ return out
102
+
103
+
104
+ # --------------------------------------------------------------------------- config
105
+
106
+ class GecTaggerConfig(PretrainedConfig):
107
+ model_type = "gec_tagger"
108
+
109
+ # NB: the field is `num_tags`, NOT `num_labels` — `num_labels` is a reserved PretrainedConfig
110
+ # property that auto-builds an id2label dict (here that would be 128802 entries) and breaks loading.
111
+ def __init__(self, encoder_name: str = "LiquidAI/mlm_phase2_bidir2_step140800", num_tags: int = 128802,
112
+ hidden_size: int = 1024, tie_replace: bool = True, multi_head: bool = False,
113
+ aux_loss_weight: float = 0.5, use_swap: bool = False, qat_applied: bool = False,
114
+ qat_group_size: int = 32, dropout: float = 0.1, **kwargs):
115
+ self.encoder_name = encoder_name
116
+ self.num_tags = num_tags
117
+ self.hidden_size = hidden_size
118
+ self.tie_replace = tie_replace
119
+ self.multi_head = multi_head
120
+ self.aux_loss_weight = aux_loss_weight
121
+ self.use_swap = use_swap
122
+ self.qat_applied = qat_applied
123
+ self.qat_group_size = qat_group_size
124
+ self.dropout = dropout
125
+ super().__init__(**kwargs)
126
+
127
+
128
+ # --------------------------------------------------------------------------- model
129
+
130
+ def _last_hidden(backbone, input_ids, attention_mask) -> torch.Tensor:
131
+ out = backbone(input_ids=input_ids, attention_mask=attention_mask)
132
+ hs = getattr(out, "last_hidden_state", None)
133
+ if hs is None and getattr(out, "hidden_states", None) is not None:
134
+ hs = out.hidden_states[-1]
135
+ if hs is None:
136
+ hs = out[0]
137
+ return hs
138
+
139
+
140
+ def _build_backbone(encoder_name: str):
141
+ """Build the bidirectional-LFM2 trunk shared across the whole encoder family (embedding / ColBERT /
142
+ encoder-MLM / token-classification / this tagger). Weights come from THIS repo's safetensors, so the
143
+ trunk is always built from config — no second encoder download.
144
+
145
+ Prefers the in-library ``transformers.Lfm2BidirectionalModel`` once the bidirectional-LFM2 family PR
146
+ lands: it is version-stable (no ``trust_remote_code`` for the trunk) and numerically identical to the
147
+ encoder repo's remote-code MLM base (verified 0.0 CPU / <1e-5 GPU by the family integration), so the
148
+ trained state_dict still loads 1:1 under ``encoder.*``. Until the class is exposed by ``transformers``
149
+ this transparently falls back to the encoder repo's own remote-code MLM class with the head stripped —
150
+ byte-identical to the original behaviour.
151
+ """
152
+ import transformers
153
+ native = getattr(transformers, "Lfm2BidirectionalModel", None)
154
+ if native is not None: # native foundation (post family-PR)
155
+ cfg = AutoConfig.from_pretrained(encoder_name) # model_type resolves natively, no remote code
156
+ try:
157
+ return native._from_config(cfg)
158
+ except AttributeError:
159
+ return native(cfg)
160
+ enc_cfg = AutoConfig.from_pretrained(encoder_name, trust_remote_code=True) # fallback: encoder remote code
161
+ return AutoModelForMaskedLM.from_config(enc_cfg, trust_remote_code=True).base_model
162
+
163
+
164
+ class GecTaggerForGEC(PreTrainedModel):
165
+ """GECToR two-head tagger. Submodule names match the training-time `spellchecker.model.GecTagger`
166
+ so the trained state_dict loads 1:1. With `tie_replace` the $REPLACE/$APPEND blocks are tied to the
167
+ encoder input embeddings (logit = proj(h) · embedding_i) rather than a free Linear(hidden, 2+2V)."""
168
+
169
+ config_class = GecTaggerConfig
170
+ base_model_prefix = "encoder"
171
+
172
+ def __init__(self, config: GecTaggerConfig):
173
+ super().__init__(config)
174
+ self._base = _rep_base(config.use_swap)
175
+ # Bidirectional-LFM2 trunk, shared with the rest of the encoder family. Weights come from this
176
+ # repo's safetensors (built from config, no second encoder download). Rides the in-library
177
+ # Lfm2BidirectionalModel once the family PR lands; falls back to the encoder's remote code today.
178
+ self.encoder = _build_backbone(config.encoder_name)
179
+ if config.qat_applied:
180
+ # dynamic import (not a top-level `from torchao...`): transformers statically scans this file
181
+ # for import lines and would otherwise REQUIRE torchao even for non-QAT models that never hit
182
+ # this branch. importlib keeps the dependency truly optional.
183
+ import importlib
184
+ qat = importlib.import_module("torchao.quantization.qat")
185
+ self.encoder = qat.Int4WeightOnlyQATQuantizer(groupsize=config.qat_group_size).prepare(self.encoder)
186
+ hidden = config.hidden_size
187
+ self.dropout = nn.Dropout(config.dropout)
188
+ self.detect_head = nn.Linear(hidden, 2)
189
+ if config.multi_head:
190
+ self.del_head = nn.Linear(hidden, 2)
191
+ self.ins_head = nn.Linear(hidden, 2)
192
+ self.sub_head = nn.Linear(hidden, 2)
193
+ if config.tie_replace:
194
+ V = (config.num_tags - self._base) // 2
195
+ assert self._base + 2 * V == config.num_tags, "tie_replace requires num_tags=base+2V"
196
+ self.vocab_size = V
197
+ self.base_head = nn.Linear(hidden, self._base)
198
+ self.replace_proj = nn.Linear(hidden, hidden)
199
+ self.append_proj = nn.Linear(hidden, hidden)
200
+ self.replace_bias = nn.Parameter(torch.zeros(V))
201
+ self.append_bias = nn.Parameter(torch.zeros(V))
202
+ else:
203
+ self.vocab_size = (config.num_tags - self._base) // 2
204
+ self.label_head = nn.Linear(hidden, config.num_tags)
205
+ self._tok = None # lazily-built tokenizer for .correct()
206
+ self._scorer = None # lazily-loaded reranker (reranker/ subfolder)
207
+ self._rerank_op = None # cached (keep_confidence, tau) operating point
208
+ self.post_init() # transformers 5.x: registers tied-weight keys etc.
209
+
210
+ def _label_logits(self, hidden):
211
+ if not self.config.tie_replace:
212
+ return self.label_head(hidden)
213
+ E = self.encoder.get_input_embeddings().weight[:self.vocab_size] # [V, hidden] tied
214
+ base = self.base_head(hidden)
215
+ rep = self.replace_proj(hidden) @ E.t() + self.replace_bias
216
+ app = self.append_proj(hidden) @ E.t() + self.append_bias
217
+ return torch.cat([base, rep, app], dim=-1)
218
+
219
+ def forward(self, input_ids, attention_mask=None, **kwargs):
220
+ if attention_mask is None:
221
+ attention_mask = torch.ones_like(input_ids)
222
+ hidden = self.dropout(_last_hidden(self.encoder, input_ids, attention_mask))
223
+ out = {"label_logits": self._label_logits(hidden), "detect_logits": self.detect_head(hidden)}
224
+ if self.config.multi_head:
225
+ out["del_logits"] = self.del_head(hidden)
226
+ out["ins_logits"] = self.ins_head(hidden)
227
+ out["sub_logits"] = self.sub_head(hidden)
228
+ return out
229
+
230
+ # ---- inference ----------------------------------------------------------
231
+ def _tokenizer(self, tokenizer=None):
232
+ if tokenizer is not None:
233
+ return tokenizer
234
+ if self._tok is None:
235
+ from transformers import AutoTokenizer
236
+ # tokenizer files are saved into this repo, so name_or_path resolves locally; fall back to encoder
237
+ src = self.name_or_path or self.config.encoder_name
238
+ try:
239
+ self._tok = AutoTokenizer.from_pretrained(src, trust_remote_code=True)
240
+ except Exception:
241
+ self._tok = AutoTokenizer.from_pretrained(self.config.encoder_name, trust_remote_code=True)
242
+ return self._tok
243
+
244
+ @torch.no_grad()
245
+ def _step(self, seqs: List[List[int]], pad_id: int, batch_size: int, keep_confidence: float,
246
+ min_error_prob: float) -> List[List[int]]:
247
+ V, use_swap = self.vocab_size, self.config.use_swap
248
+ device = self.device
249
+ new_seqs: List[List[int]] = []
250
+ for i in range(0, len(seqs), batch_size):
251
+ chunk = seqs[i:i + batch_size]
252
+ maxlen = max(len(s) for s in chunk)
253
+ ids = torch.full((len(chunk), maxlen), pad_id, dtype=torch.long)
254
+ mask = torch.zeros((len(chunk), maxlen), dtype=torch.long)
255
+ for b, s in enumerate(chunk):
256
+ ids[b, :len(s)] = torch.tensor(s)
257
+ mask[b, :len(s)] = 1
258
+ res = self(ids.to(device), mask.to(device))
259
+ label_logits = res["label_logits"]
260
+ label_logits[..., KEEP_ID] += keep_confidence
261
+ best = label_logits.argmax(-1)
262
+ err_prob = res["detect_logits"].softmax(-1)[..., INCORRECT]
263
+ for b, s in enumerate(chunk):
264
+ tags = []
265
+ for pos in range(len(s)):
266
+ lid = int(best[b, pos])
267
+ ok = lid != KEEP_ID and float(err_prob[b, pos]) >= min_error_prob
268
+ tags.append(id_to_tag(lid, V, use_swap) if ok else "$KEEP")
269
+ new_seqs.append(apply_tags(s, tags))
270
+ return new_seqs
271
+
272
+ def _tag_correct(self, texts, tok, max_iter, max_len, batch_size, keep_confidence,
273
+ min_error_prob) -> List[str]:
274
+ """Tagger-only iterative decode (the original `.correct()` body). Returns a corrected string
275
+ per input. `keep_confidence` < 0 over-generates edits (used by the reranker)."""
276
+ bos_id = tok.bos_token_id if tok.bos_token_id is not None else (tok.cls_token_id or 0)
277
+ pad_id = tok.pad_token_id if tok.pad_token_id is not None else 0
278
+ cur = [[bos_id] + tok.encode(t, add_special_tokens=False)[:max_len - 1] for t in texts]
279
+ active = list(range(len(cur)))
280
+ for _ in range(max_iter):
281
+ if not active:
282
+ break
283
+ updated = self._step([cur[i] for i in active], pad_id, batch_size,
284
+ keep_confidence, min_error_prob)
285
+ still = []
286
+ for idx, new in zip(active, updated):
287
+ new = [bos_id] + new
288
+ if new != cur[idx]:
289
+ cur[idx] = new
290
+ still.append(idx)
291
+ active = still
292
+ return [tok.decode(s[1:], skip_special_tokens=True).strip() for s in cur]
293
+
294
+ # ---- reranker (lazy, from this repo's reranker/ subfolder) ---------------
295
+ def _reranker(self):
296
+ """Lazily load (scorer, keep_confidence, tau) from the SAME repo's `reranker/` subfolder.
297
+ Returns None if no reranker is bundled (then `.correct()` falls back to tagger-only). The
298
+ scorer + operating point ship next to the model weights; nothing is fetched from elsewhere."""
299
+ if self._scorer is not None:
300
+ return self._scorer, self._rerank_op
301
+ import json
302
+ import os
303
+ rr = _reranker_mod
304
+ if rr is None: # companion not present -> tagger-only
305
+ print("[gectagger] reranker companion module not bundled; using tagger-only .correct()")
306
+ self._scorer, self._rerank_op = False, None
307
+ return False, None
308
+ # locate the reranker/ subfolder: local export dir, or fetch from the hub repo by id
309
+ base = self.name_or_path or ""
310
+ scorer_dir = os.path.join(base, "reranker") if base else ""
311
+ if not (scorer_dir and os.path.isfile(os.path.join(scorer_dir, "scorer_config.json"))):
312
+ try: # not a local dir -> resolve the hub repo
313
+ from huggingface_hub import snapshot_download
314
+ tok_env = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
315
+ local = snapshot_download(repo_id=base, allow_patterns=["reranker/*"], token=tok_env)
316
+ scorer_dir = os.path.join(local, "reranker")
317
+ except Exception as e:
318
+ print(f"[gectagger] reranker not available ({e}); using tagger-only .correct()")
319
+ self._scorer, self._rerank_op = False, None
320
+ return False, None
321
+ if not os.path.isfile(os.path.join(scorer_dir, "scorer_config.json")):
322
+ print(f"[gectagger] no reranker/ in {base}; using tagger-only .correct()")
323
+ self._scorer, self._rerank_op = False, None
324
+ return False, None
325
+ kc, tau = -0.25, 0.4 # shipped default operating point
326
+ op_path = os.path.join(scorer_dir, "operating_point.json")
327
+ if os.path.isfile(op_path):
328
+ op = json.load(open(op_path))
329
+ kc = float(op.get("keep_confidence", kc))
330
+ tau = float(op.get("tau", tau))
331
+ # match the tagger's ACTUAL weight dtype (read from a real parameter, not self.dtype which is
332
+ # unreliable when the from_config encoder carries fp32 buffers) so the shared-shape matmuls in
333
+ # the scorer don't hit a Float-vs-Half mismatch (the Space casts the whole model to fp16).
334
+ try:
335
+ tagger_dtype = next(self.base_head.parameters()).dtype
336
+ except Exception:
337
+ tagger_dtype = self.dtype
338
+ scorer = rr.EditScorer.load(scorer_dir).to(self.device).to(tagger_dtype)
339
+ scorer.eval()
340
+ self._scorer, self._rerank_op = scorer, (kc, tau)
341
+ print(f"[gectagger] reranker loaded from {scorer_dir} (mode={scorer.mode}, "
342
+ f"type_feature={scorer.type_feature}); operating point keep_confidence={kc} tau={tau}")
343
+ return self._scorer, self._rerank_op
344
+
345
+ @torch.no_grad()
346
+ def correct(self, texts, tokenizer=None, max_iter: int = 3, max_len: int = 128, batch_size: int = 64,
347
+ keep_confidence: float = 0.0, min_error_prob: float = 0.0, rerank: bool = True) -> List[str]:
348
+ """Correct a list of (whitespace-tokenized) sentences. Iterates tag->apply until the text stops
349
+ changing or `max_iter` is reached. `min_error_prob` / `keep_confidence` are the GECToR precision
350
+ knobs (higher => fewer edits).
351
+
352
+ rerank=True (default): run the FULL system — let the tagger over-generate at the bundled
353
+ operating point's `keep_confidence`, then a per-edit scorer (loaded once from this repo's
354
+ `reranker/` subfolder) keeps only edits with P(correct) >= tau and re-applies them to the
355
+ source. This is the published MASTER-composite operating point. If no reranker is bundled, it
356
+ transparently falls back to tagger-only. rerank=False: exact tagger-only behaviour, using the
357
+ `keep_confidence` / `min_error_prob` passed in."""
358
+ single = isinstance(texts, str)
359
+ if single:
360
+ texts = [texts]
361
+ tok = self._tokenizer(tokenizer)
362
+ self.eval()
363
+
364
+ if not rerank:
365
+ out = self._tag_correct(texts, tok, max_iter, max_len, batch_size,
366
+ keep_confidence, min_error_prob)
367
+ return out[0] if single else out
368
+
369
+ scorer, op = self._reranker()
370
+ if not scorer: # no reranker bundled -> tagger-only fallback
371
+ out = self._tag_correct(texts, tok, max_iter, max_len, batch_size,
372
+ keep_confidence, min_error_prob)
373
+ return out[0] if single else out
374
+ kc, tau = op
375
+ # over-generate with the tagger at the scorer's training operating point (negative kc), then
376
+ # filter per-edit. min_error_prob stays at 0 here so the scorer — not the detection gate — is
377
+ # the precision lever (this is the configuration the published MASTER was measured at).
378
+ hyps = self._tag_correct(texts, tok, max_iter, max_len, batch_size, kc, 0.0)
379
+ out = _reranker_mod.rerank(scorer, tok, list(texts), hyps, tau, self.device,
380
+ batch_size=batch_size)
381
+ return out[0] if single else out
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers>=4.44
2
+ torch>=2.1
3
+ safetensors
4
+ huggingface_hub>=0.26
5
+ errant==3.0.2
6
+ spacy==3.8.14
7
+ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
reranker/operating_point.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "keep_confidence": 0.0,
3
+ "tau": 0.3,
4
+ "MASTER": 0.6587,
5
+ "control_master": 0.631,
6
+ "scorer_run": "runs/reranker/en_v2_rr/best",
7
+ "report": "reranker_en_v2_rr.json",
8
+ "grid": [
9
+ {
10
+ "keep_confidence": -0.25,
11
+ "tau": 0.2,
12
+ "MASTER": 0.6452,
13
+ "MASTER_V2": 0.6864,
14
+ "precision": 0.6054,
15
+ "recall": 0.3411,
16
+ "f0.5": 0.5242,
17
+ "group_means": {
18
+ "native": 0.3526,
19
+ "learner": 0.4991,
20
+ "robustness": 0.94,
21
+ "precision": 0.9355,
22
+ "typo": 0.7538
23
+ },
24
+ "fp_clean": 0.9355,
25
+ "per_eval": {
26
+ "ndev_native": 0.495,
27
+ "cweb_g": 0.3111,
28
+ "cweb_s": 0.2518,
29
+ "bea_dev": 0.4989,
30
+ "conll14": 0.4799,
31
+ "fce_test": 0.5186,
32
+ "robustness": 0.94,
33
+ "fp_clean": 0.9355,
34
+ "github_typo_test": 0.6545,
35
+ "garble": 0.8476,
36
+ "native_conf": 0.7593
37
+ }
38
+ },
39
+ {
40
+ "keep_confidence": -0.25,
41
+ "tau": 0.25,
42
+ "MASTER": 0.6482,
43
+ "MASTER_V2": 0.6901,
44
+ "precision": 0.6206,
45
+ "recall": 0.3378,
46
+ "f0.5": 0.5316,
47
+ "group_means": {
48
+ "native": 0.3577,
49
+ "learner": 0.5054,
50
+ "robustness": 0.9388,
51
+ "precision": 0.9355,
52
+ "typo": 0.7621
53
+ },
54
+ "fp_clean": 0.9355,
55
+ "per_eval": {
56
+ "ndev_native": 0.5034,
57
+ "cweb_g": 0.3147,
58
+ "cweb_s": 0.2551,
59
+ "bea_dev": 0.5072,
60
+ "conll14": 0.4817,
61
+ "fce_test": 0.5274,
62
+ "robustness": 0.9388,
63
+ "fp_clean": 0.9355,
64
+ "github_typo_test": 0.662,
65
+ "garble": 0.8562,
66
+ "native_conf": 0.7681
67
+ }
68
+ },
69
+ {
70
+ "keep_confidence": -0.25,
71
+ "tau": 0.3,
72
+ "MASTER": 0.6502,
73
+ "MASTER_V2": 0.6932,
74
+ "precision": 0.6367,
75
+ "recall": 0.3313,
76
+ "f0.5": 0.5376,
77
+ "group_means": {
78
+ "native": 0.3621,
79
+ "learner": 0.5099,
80
+ "robustness": 0.9362,
81
+ "precision": 0.9355,
82
+ "typo": 0.7716
83
+ },
84
+ "fp_clean": 0.9355,
85
+ "per_eval": {
86
+ "ndev_native": 0.5111,
87
+ "cweb_g": 0.3163,
88
+ "cweb_s": 0.259,
89
+ "bea_dev": 0.5099,
90
+ "conll14": 0.4821,
91
+ "fce_test": 0.5376,
92
+ "robustness": 0.9362,
93
+ "fp_clean": 0.9355,
94
+ "github_typo_test": 0.6705,
95
+ "garble": 0.8671,
96
+ "native_conf": 0.7771
97
+ }
98
+ },
99
+ {
100
+ "keep_confidence": -0.25,
101
+ "tau": 0.4,
102
+ "MASTER": 0.6518,
103
+ "MASTER_V2": 0.6979,
104
+ "precision": 0.6765,
105
+ "recall": 0.3072,
106
+ "f0.5": 0.5454,
107
+ "group_means": {
108
+ "native": 0.3653,
109
+ "learner": 0.511,
110
+ "robustness": 0.9058,
111
+ "precision": 0.9677,
112
+ "typo": 0.7881
113
+ },
114
+ "fp_clean": 0.9677,
115
+ "per_eval": {
116
+ "ndev_native": 0.5178,
117
+ "cweb_g": 0.3143,
118
+ "cweb_s": 0.2639,
119
+ "bea_dev": 0.5086,
120
+ "conll14": 0.4734,
121
+ "fce_test": 0.5511,
122
+ "robustness": 0.9058,
123
+ "fp_clean": 0.9677,
124
+ "github_typo_test": 0.6879,
125
+ "garble": 0.8917,
126
+ "native_conf": 0.7846
127
+ }
128
+ },
129
+ {
130
+ "keep_confidence": -0.5,
131
+ "tau": 0.2,
132
+ "MASTER": 0.6426,
133
+ "MASTER_V2": 0.6785,
134
+ "precision": 0.5737,
135
+ "recall": 0.3623,
136
+ "f0.5": 0.5137,
137
+ "group_means": {
138
+ "native": 0.3514,
139
+ "learner": 0.4967,
140
+ "robustness": 0.9325,
141
+ "precision": 0.9355,
142
+ "typo": 0.7247
143
+ },
144
+ "fp_clean": 0.9355,
145
+ "per_eval": {
146
+ "ndev_native": 0.4931,
147
+ "cweb_g": 0.3102,
148
+ "cweb_s": 0.251,
149
+ "bea_dev": 0.4974,
150
+ "conll14": 0.482,
151
+ "fce_test": 0.5106,
152
+ "robustness": 0.9325,
153
+ "fp_clean": 0.9355,
154
+ "github_typo_test": 0.6203,
155
+ "garble": 0.8356,
156
+ "native_conf": 0.7182
157
+ }
158
+ },
159
+ {
160
+ "keep_confidence": -0.5,
161
+ "tau": 0.25,
162
+ "MASTER": 0.6461,
163
+ "MASTER_V2": 0.6831,
164
+ "precision": 0.5898,
165
+ "recall": 0.358,
166
+ "f0.5": 0.5222,
167
+ "group_means": {
168
+ "native": 0.357,
169
+ "learner": 0.5044,
170
+ "robustness": 0.9312,
171
+ "precision": 0.9355,
172
+ "typo": 0.7364
173
+ },
174
+ "fp_clean": 0.9355,
175
+ "per_eval": {
176
+ "ndev_native": 0.5018,
177
+ "cweb_g": 0.315,
178
+ "cweb_s": 0.2543,
179
+ "bea_dev": 0.5064,
180
+ "conll14": 0.4866,
181
+ "fce_test": 0.5203,
182
+ "robustness": 0.9312,
183
+ "fp_clean": 0.9355,
184
+ "github_typo_test": 0.6281,
185
+ "garble": 0.847,
186
+ "native_conf": 0.7341
187
+ }
188
+ },
189
+ {
190
+ "keep_confidence": -0.5,
191
+ "tau": 0.3,
192
+ "MASTER": 0.6491,
193
+ "MASTER_V2": 0.6881,
194
+ "precision": 0.6076,
195
+ "recall": 0.3503,
196
+ "f0.5": 0.5298,
197
+ "group_means": {
198
+ "native": 0.3632,
199
+ "learner": 0.5108,
200
+ "robustness": 0.9283,
201
+ "precision": 0.9355,
202
+ "typo": 0.7517
203
+ },
204
+ "fp_clean": 0.9355,
205
+ "per_eval": {
206
+ "ndev_native": 0.5131,
207
+ "cweb_g": 0.3178,
208
+ "cweb_s": 0.2587,
209
+ "bea_dev": 0.5118,
210
+ "conll14": 0.49,
211
+ "fce_test": 0.5305,
212
+ "robustness": 0.9283,
213
+ "fp_clean": 0.9355,
214
+ "github_typo_test": 0.6373,
215
+ "garble": 0.8585,
216
+ "native_conf": 0.7593
217
+ }
218
+ },
219
+ {
220
+ "keep_confidence": -0.5,
221
+ "tau": 0.4,
222
+ "MASTER": 0.6527,
223
+ "MASTER_V2": 0.6949,
224
+ "precision": 0.6515,
225
+ "recall": 0.3212,
226
+ "f0.5": 0.5404,
227
+ "group_means": {
228
+ "native": 0.367,
229
+ "learner": 0.5145,
230
+ "robustness": 0.9031,
231
+ "precision": 0.9677,
232
+ "typo": 0.7712
233
+ },
234
+ "fp_clean": 0.9677,
235
+ "per_eval": {
236
+ "ndev_native": 0.5213,
237
+ "cweb_g": 0.3199,
238
+ "cweb_s": 0.2597,
239
+ "bea_dev": 0.5108,
240
+ "conll14": 0.4838,
241
+ "fce_test": 0.5489,
242
+ "robustness": 0.9031,
243
+ "fp_clean": 0.9677,
244
+ "github_typo_test": 0.6621,
245
+ "garble": 0.8857,
246
+ "native_conf": 0.7658
247
+ }
248
+ },
249
+ {
250
+ "keep_confidence": 0.0,
251
+ "tau": 0.2,
252
+ "MASTER": 0.6552,
253
+ "MASTER_V2": 0.7006,
254
+ "precision": 0.6337,
255
+ "recall": 0.3147,
256
+ "f0.5": 0.5269,
257
+ "group_means": {
258
+ "native": 0.3549,
259
+ "learner": 0.489,
260
+ "robustness": 0.9324,
261
+ "precision": 1.0,
262
+ "typo": 0.7714
263
+ },
264
+ "fp_clean": 1.0,
265
+ "per_eval": {
266
+ "ndev_native": 0.5,
267
+ "cweb_g": 0.3046,
268
+ "cweb_s": 0.2601,
269
+ "bea_dev": 0.4921,
270
+ "conll14": 0.4546,
271
+ "fce_test": 0.5202,
272
+ "robustness": 0.9324,
273
+ "fp_clean": 1.0,
274
+ "github_typo_test": 0.6787,
275
+ "garble": 0.8529,
276
+ "native_conf": 0.7826
277
+ }
278
+ },
279
+ {
280
+ "keep_confidence": 0.0,
281
+ "tau": 0.25,
282
+ "MASTER": 0.6577,
283
+ "MASTER_V2": 0.7033,
284
+ "precision": 0.6475,
285
+ "recall": 0.3125,
286
+ "f0.5": 0.5332,
287
+ "group_means": {
288
+ "native": 0.3596,
289
+ "learner": 0.4941,
290
+ "robustness": 0.9311,
291
+ "precision": 1.0,
292
+ "typo": 0.7763
293
+ },
294
+ "fp_clean": 1.0,
295
+ "per_eval": {
296
+ "ndev_native": 0.5062,
297
+ "cweb_g": 0.3095,
298
+ "cweb_s": 0.2631,
299
+ "bea_dev": 0.4984,
300
+ "conll14": 0.4558,
301
+ "fce_test": 0.5282,
302
+ "robustness": 0.9311,
303
+ "fp_clean": 1.0,
304
+ "github_typo_test": 0.6851,
305
+ "garble": 0.8611,
306
+ "native_conf": 0.7826
307
+ }
308
+ },
309
+ {
310
+ "keep_confidence": 0.0,
311
+ "tau": 0.3,
312
+ "MASTER": 0.6587,
313
+ "MASTER_V2": 0.7053,
314
+ "precision": 0.6636,
315
+ "recall": 0.3076,
316
+ "f0.5": 0.5389,
317
+ "group_means": {
318
+ "native": 0.3622,
319
+ "learner": 0.499,
320
+ "robustness": 0.9255,
321
+ "precision": 1.0,
322
+ "typo": 0.7854
323
+ },
324
+ "fp_clean": 1.0,
325
+ "per_eval": {
326
+ "ndev_native": 0.5124,
327
+ "cweb_g": 0.309,
328
+ "cweb_s": 0.2653,
329
+ "bea_dev": 0.501,
330
+ "conll14": 0.4575,
331
+ "fce_test": 0.5385,
332
+ "robustness": 0.9255,
333
+ "fp_clean": 1.0,
334
+ "github_typo_test": 0.6933,
335
+ "garble": 0.8711,
336
+ "native_conf": 0.7918
337
+ }
338
+ },
339
+ {
340
+ "keep_confidence": 0.0,
341
+ "tau": 0.4,
342
+ "MASTER": 0.6545,
343
+ "MASTER_V2": 0.7045,
344
+ "precision": 0.7013,
345
+ "recall": 0.2881,
346
+ "f0.5": 0.545,
347
+ "group_means": {
348
+ "native": 0.3656,
349
+ "learner": 0.4982,
350
+ "robustness": 0.9024,
351
+ "precision": 1.0,
352
+ "typo": 0.8004
353
+ },
354
+ "fp_clean": 1.0,
355
+ "per_eval": {
356
+ "ndev_native": 0.5208,
357
+ "cweb_g": 0.3057,
358
+ "cweb_s": 0.2702,
359
+ "bea_dev": 0.4994,
360
+ "conll14": 0.4478,
361
+ "fce_test": 0.5475,
362
+ "robustness": 0.9024,
363
+ "fp_clean": 1.0,
364
+ "github_typo_test": 0.7092,
365
+ "garble": 0.892,
366
+ "native_conf": 0.8
367
+ }
368
+ }
369
+ ]
370
+ }
reranker/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:628d648c0754a5a50838f9251491fa4a116a59fb11d035849e7b00e4ab51c725
3
+ size 1418022719
reranker/scorer_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "encoder_name": "LiquidAI/LFM2.5-Encoder-350M",
3
+ "hidden_size": 1024,
4
+ "mode": "cross",
5
+ "type_feature": true
6
+ }
reranker_gectagger.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained edit reranker that ships INSIDE the Hugging Face model repo alongside
2
+ `modeling_gectagger.py` and is loaded via `trust_remote_code=True`. It must NOT import the
3
+ `spellchecker` package (end users / the Space won't have it) and must NOT depend on `errant`/`spaCy`
4
+ (the Space ships only transformers + safetensors). Everything the per-edit reranker needs — the
5
+ EditScorer architecture, the candidate-input construction, a dependency-free word-level edit
6
+ extractor, and the over-generate -> score -> filter -> re-apply logic — is inlined here.
7
+
8
+ This is the inference twin of `spellchecker/reranker.py` (training/eval code). The scorer is a
9
+ shared-backbone binary classifier (EditScorer-style, Sorokin 2022): the tagger over-generates edits at
10
+ a negative `keep_confidence`, each proposed edit is scored P(correct), and only edits with P >= tau are
11
+ kept and re-applied to the source. The shipped scorer is the `cross` variant with a per-ERRANT-type
12
+ feature; its weights + operating point live in the SAME repo's `reranker/` subfolder, lazily loaded on
13
+ first `.correct(..., rerank=True)`.
14
+
15
+ FIDELITY NOTE — edit extraction. The scorer was trained and the published MASTER (0.6642) measured with
16
+ ERRANT word-level alignment (`tokenise=False`) of source->hypothesis. ERRANT needs spaCy, which is not
17
+ available at serve time, so this module extracts edits with a dependency-free `difflib` word diff and
18
+ recovers ERRANT-style minimal edits by splitting aligned (replace) blocks token-by-token where the
19
+ block is length-preserving — the common case ERRANT also splits. The candidate char-span construction
20
+ and scorer input are otherwise byte-identical to the training path, so a candidate's score matches.
21
+ `type_feature` types are coarse (M/U/R + a couple of cheap subtypes) rather than full ERRANT types; the
22
+ type only feeds a hash bucket, so coarse types still calibrate per broad error class. See the local
23
+ verification in the publish flow for the measured tagger-only vs reranked behaviour on the exported repo.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import difflib
28
+ import json
29
+ import os
30
+ import zlib
31
+ from collections import defaultdict
32
+ from typing import Dict, List, Sequence, Tuple
33
+
34
+ import torch
35
+ import torch.nn as nn
36
+ from transformers import AutoConfig, AutoModelForMaskedLM
37
+
38
+ # --------------------------------------------------------------------------- encoder trunk
39
+
40
+ def _backbone(name: str, pretrained: bool = False):
41
+ """(backbone_module, hidden_size). The shared bidirectional-LFM2 trunk (same as the tagger's).
42
+
43
+ Prefers the in-library ``transformers.Lfm2BidirectionalModel`` once the bidirectional-LFM2 family PR
44
+ lands — version-stable, no remote code for the trunk, numerically identical to the encoder repo's
45
+ remote-code MLM base (verified 0.0 CPU / <1e-5 GPU), so the scorer's state_dict still loads 1:1 under
46
+ ``encoder.*``. Until then it falls back to the encoder repo's remote-code MLM class with the head
47
+ stripped (the original behaviour). For inference inside the published repo we build from config
48
+ (pretrained=False) and load the scorer's own weights — no second encoder download."""
49
+ import transformers
50
+ native = getattr(transformers, "Lfm2BidirectionalModel", None)
51
+ if native is not None: # native foundation (post family-PR)
52
+ config = AutoConfig.from_pretrained(name) # model_type resolves natively, no remote code
53
+ hidden = getattr(config, "hidden_size", None) or getattr(config, "d_model", None) or 1024
54
+ if pretrained:
55
+ backbone = native.from_pretrained(name)
56
+ else:
57
+ try:
58
+ backbone = native._from_config(config)
59
+ except AttributeError:
60
+ backbone = native(config)
61
+ return backbone, hidden
62
+ config = AutoConfig.from_pretrained(name, trust_remote_code=True) # fallback: encoder remote code
63
+ hidden = getattr(config, "hidden_size", None) or getattr(config, "d_model", None) or 1024
64
+ if pretrained:
65
+ mlm = AutoModelForMaskedLM.from_pretrained(name, trust_remote_code=True)
66
+ else:
67
+ mlm = AutoModelForMaskedLM.from_config(config, trust_remote_code=True)
68
+ return mlm.base_model, hidden
69
+
70
+
71
+ def _last_hidden(backbone, input_ids, attention_mask) -> torch.Tensor:
72
+ out = backbone(input_ids=input_ids, attention_mask=attention_mask)
73
+ hs = getattr(out, "last_hidden_state", None)
74
+ if hs is None and getattr(out, "hidden_states", None) is not None:
75
+ hs = out.hidden_states[-1]
76
+ if hs is None:
77
+ hs = out[0]
78
+ return hs
79
+
80
+
81
+ # --------------------------------------------------------------- candidate input construction
82
+ # (byte-identical to spellchecker.reranker so a candidate's encoder input matches the trained scorer)
83
+
84
+ def apply_edits(tokens: List[str], edits: List[Dict]) -> List[str]:
85
+ """Apply token-span edits to `tokens` (same semantics as spellchecker.edits.apply_edits)."""
86
+ out: List[str] = []
87
+ prev = 0
88
+ for e in sorted(edits, key=lambda e: (int(e["start"]), int(e["end"]))):
89
+ start, end = int(e["start"]), int(e["end"])
90
+ if start < prev: # overlapping: drop
91
+ continue
92
+ out.extend(tokens[prev:start])
93
+ repl = str(e["replacement"])
94
+ if repl:
95
+ out.extend(repl.split())
96
+ prev = end
97
+ out.extend(tokens[prev:])
98
+ return out
99
+
100
+
101
+ def build_scorer_input(src_tokens: Sequence[str], edit: Dict) -> Tuple[str, int, int]:
102
+ a, b = int(edit["start"]), int(edit["end"])
103
+ rep = str(edit["replacement"]).split()
104
+ out = list(src_tokens[:a]) + rep + list(src_tokens[b:])
105
+ text = " ".join(out)
106
+ if rep:
107
+ c0 = len(" ".join(out[:a])) + (1 if a > 0 else 0)
108
+ c1 = c0 + len(" ".join(rep))
109
+ else: # deletion: pool over flanking tokens
110
+ left, right = max(a - 1, 0), min(a + 1, len(out))
111
+ c0 = len(" ".join(out[:left])) + (1 if left > 0 else 0)
112
+ c1 = c0 + len(" ".join(out[left:right]))
113
+ if c1 <= c0:
114
+ c0, c1 = 0, max(len(text), 1)
115
+ return text, c0, c1
116
+
117
+
118
+ def build_source_input(src_tokens: Sequence[str], edit: Dict) -> Tuple[str, int, int]:
119
+ a, b = int(edit["start"]), int(edit["end"])
120
+ text = " ".join(src_tokens)
121
+ if a < b:
122
+ c0 = len(" ".join(src_tokens[:a])) + (1 if a > 0 else 0)
123
+ c1 = c0 + len(" ".join(src_tokens[a:b]))
124
+ else: # insertion: pool over the gap's neighbours
125
+ left, right = max(a - 1, 0), min(a + 1, len(src_tokens))
126
+ c0 = len(" ".join(src_tokens[:left])) + (1 if left > 0 else 0)
127
+ c1 = c0 + len(" ".join(src_tokens[left:right]))
128
+ if c1 <= c0:
129
+ c0, c1 = 0, max(len(text), 1)
130
+ return text, c0, c1
131
+
132
+
133
+ def sep_token(tokenizer) -> str:
134
+ return tokenizer.sep_token or tokenizer.eos_token or "||"
135
+
136
+
137
+ def build_cross_input(src_tokens: Sequence[str], edit: Dict, sep: str
138
+ ) -> Tuple[str, int, int, int, int]:
139
+ s_text, s0, s1 = build_source_input(src_tokens, edit)
140
+ e_text, e0, e1 = build_scorer_input(src_tokens, edit)
141
+ text = f"{s_text} {sep} {e_text}"
142
+ off = len(s_text) + len(sep) + 2
143
+ return text, off + e0, off + e1, s0, s1
144
+
145
+
146
+ def type_bucket(edit_type: str, buckets: int = 64) -> int:
147
+ return zlib.crc32(str(edit_type).encode()) % buckets
148
+
149
+
150
+ def encode_candidates(tokenizer, items: List[Tuple[str, int, int]], max_len: int = 160):
151
+ texts = [t for t, _, _ in items]
152
+ enc = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=max_len,
153
+ return_offsets_mapping=True)
154
+ offsets = enc.pop("offset_mapping")
155
+ span = torch.zeros_like(enc["attention_mask"])
156
+ for i, (_, c0, c1) in enumerate(items):
157
+ for j, (o0, o1) in enumerate(offsets[i].tolist()):
158
+ if enc["attention_mask"][i, j] and o1 > o0 and o0 < c1 and o1 > c0:
159
+ span[i, j] = 1
160
+ if not span[i].any():
161
+ span[i] = enc["attention_mask"][i]
162
+ return enc["input_ids"], enc["attention_mask"], span
163
+
164
+
165
+ def encode_cross(tokenizer, items: List[Tuple[str, int, int, int, int]], max_len: int = 320):
166
+ texts = [t for t, *_ in items]
167
+ enc = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=max_len,
168
+ return_offsets_mapping=True)
169
+ offsets = enc.pop("offset_mapping")
170
+ spans = [torch.zeros_like(enc["attention_mask"]) for _ in range(2)]
171
+ for i, (_, e0, e1, s0, s1) in enumerate(items):
172
+ for j, (o0, o1) in enumerate(offsets[i].tolist()):
173
+ if not enc["attention_mask"][i, j] or o1 <= o0:
174
+ continue
175
+ if o0 < e1 and o1 > e0:
176
+ spans[0][i, j] = 1
177
+ if o0 < s1 and o1 > s0:
178
+ spans[1][i, j] = 1
179
+ for s in spans:
180
+ if not s[i].any():
181
+ s[i] = enc["attention_mask"][i]
182
+ return enc["input_ids"], enc["attention_mask"], spans[0], spans[1]
183
+
184
+
185
+ # --------------------------------------------------------------- dependency-free edit extraction
186
+
187
+ _VOWELS = set("aeiouAEIOU")
188
+
189
+
190
+ def _coarse_type(src_span: List[str], rep: List[str]) -> str:
191
+ """Coarse ERRANT-ish type for the per-type feature hash. Full ERRANT types need spaCy; the type
192
+ only feeds a 64-way hash bucket, so a broad class (M/U/R + a couple cheap subtypes) is enough to
193
+ let the head calibrate per error family. Mirrors the M/U/R coarse scheme of edits.align_generic."""
194
+ if not src_span:
195
+ return "M" # missing -> insertion
196
+ if not rep:
197
+ return "U" # unnecessary -> deletion
198
+ if len(src_span) == 1 and len(rep) == 1:
199
+ a, b = src_span[0], rep[0]
200
+ la, lb = a.lower(), b.lower()
201
+ if la == lb:
202
+ return "R:ORTH" # casing only
203
+ if not any(ch.isalnum() for ch in a) and not any(ch.isalnum() for ch in b):
204
+ return "R:PUNCT"
205
+ # cheap spelling cue: same first letter & similar length & shared letter multiset
206
+ if a and b and la[0] == lb[0] and abs(len(a) - len(b)) <= 2:
207
+ return "R:SPELL"
208
+ return "R:OTHER"
209
+
210
+
211
+ def _char_sim(a: str, b: str) -> float:
212
+ """SequenceMatcher ratio on characters (cheap stand-in for ERRANT's lemma/char substitution cost)."""
213
+ if a == b:
214
+ return 1.0
215
+ return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio()
216
+
217
+
218
+ def _align_block(src: List[str], tgt: List[str], i0: int, sub_thresh: float = 0.30) -> List[Dict]:
219
+ """Levenshtein-align a difflib `replace` block at the TOKEN level (this is the core of what ERRANT
220
+ does before its linguistic merge): a token pairs with another as a SUBSTITUTION only when they are
221
+ char-similar enough (>= sub_thresh), otherwise the diff is resolved as a DELETE + INSERT at the
222
+ junction. Emits minimal per-position edits with absolute offsets (block starts at source index i0).
223
+ This recovers ERRANT's split of e.g. `than a` into R:`than` + M:`a`, which a single merged
224
+ candidate would not — the recall the scale fidelity check showed difflib was dropping."""
225
+ m, n = len(src), len(tgt)
226
+ INS, DEL = 1.0, 1.0 # unit cost for an unmatched token
227
+ # DP edit distance with substitution cost = 1 - char_sim (cheap matches preferred as subs)
228
+ cost = [[0.0] * (n + 1) for _ in range(m + 1)]
229
+ bt = [[None] * (n + 1) for _ in range(m + 1)]
230
+ for i in range(1, m + 1):
231
+ cost[i][0] = i * DEL; bt[i][0] = "d"
232
+ for j in range(1, n + 1):
233
+ cost[0][j] = j * INS; bt[0][j] = "i"
234
+ for i in range(1, m + 1):
235
+ for j in range(1, n + 1):
236
+ sub = cost[i - 1][j - 1] + (1.0 - _char_sim(src[i - 1], tgt[j - 1]))
237
+ dele = cost[i - 1][j] + DEL
238
+ ins = cost[i][j - 1] + INS
239
+ best = min(sub, dele, ins)
240
+ cost[i][j] = best
241
+ bt[i][j] = "s" if best == sub else ("d" if best == dele else "i")
242
+ # backtrace into aligned ops
243
+ ops = []
244
+ i, j = m, n
245
+ while i > 0 or j > 0:
246
+ step = bt[i][j]
247
+ if step == "s":
248
+ ops.append(("s", i - 1, j - 1)); i -= 1; j -= 1
249
+ elif step == "d":
250
+ ops.append(("d", i - 1, None)); i -= 1
251
+ else:
252
+ ops.append(("i", i, j - 1)); j -= 1 # insert before source position i
253
+ ops.reverse()
254
+ edits: List[Dict] = []
255
+ for kind, si, tj in ops:
256
+ if kind == "s":
257
+ a, b = src[si], tgt[tj]
258
+ if a == b:
259
+ continue
260
+ # a poor "substitution" (char-dissimilar) is really a delete+insert at this junction
261
+ if _char_sim(a, b) < sub_thresh:
262
+ edits.append({"start": i0 + si, "end": i0 + si + 1, "replacement": "",
263
+ "type": _coarse_type([a], [])})
264
+ edits.append({"start": i0 + si + 1, "end": i0 + si + 1, "replacement": b,
265
+ "type": _coarse_type([], [b])})
266
+ else:
267
+ edits.append({"start": i0 + si, "end": i0 + si + 1, "replacement": b,
268
+ "type": _coarse_type([a], [b])})
269
+ elif kind == "d":
270
+ edits.append({"start": i0 + si, "end": i0 + si + 1, "replacement": "",
271
+ "type": _coarse_type([src[si]], [])})
272
+ else: # insert before source index si
273
+ edits.append({"start": i0 + si, "end": i0 + si, "replacement": tgt[tj],
274
+ "type": _coarse_type([], [tgt[tj]])})
275
+ return edits
276
+
277
+
278
+ _ERRANT_ANNOTATOR = None
279
+ _ERRANT_TRIED = False
280
+
281
+
282
+ def _errant_edits(src: str, hyp: str):
283
+ """ERRANT word-level edits (tokenise=False) — the SAME alignment the scorer was trained and the
284
+ published MASTER measured on. Returns None if `errant` (and its spaCy model) is not installed, so
285
+ the caller falls back to the difflib extractor. ERRANT's linguistically-merged minimal edits are
286
+ the granularity the cross+type scorer expects; reproducing them keeps the published metric intact."""
287
+ global _ERRANT_ANNOTATOR, _ERRANT_TRIED
288
+ if _ERRANT_ANNOTATOR is None:
289
+ if _ERRANT_TRIED:
290
+ return None
291
+ _ERRANT_TRIED = True
292
+ try:
293
+ import errant
294
+ _ERRANT_ANNOTATOR = errant.load("en")
295
+ except Exception as e:
296
+ print(f"[gectagger] errant unavailable ({type(e).__name__}); reranker edit extraction "
297
+ f"falls back to difflib (slightly lower recall than the ERRANT-measured operating "
298
+ f"point). Install `errant` for the published behaviour.")
299
+ return None
300
+ ann = _ERRANT_ANNOTATOR
301
+ orig, cor = ann.parse(src, False), ann.parse(hyp, False)
302
+ out = []
303
+ for e in ann.annotate(orig, cor):
304
+ out.append({"start": int(e.o_start), "end": int(e.o_end),
305
+ "replacement": e.c_str, "type": e.type})
306
+ return out
307
+
308
+
309
+ def _difflib_edits(src: str, hyp: str) -> List[Dict]:
310
+ """Dependency-free fallback: difflib word diff, `replace` blocks resolved by a token-level
311
+ Levenshtein alignment (_align_block) into minimal sub/ins/del edits. Close to ERRANT but not exact
312
+ (no linguistic merge / typing); used only when errant is not importable."""
313
+ s, t = src.split(), hyp.split()
314
+ edits: List[Dict] = []
315
+ for op, i1, i2, j1, j2 in difflib.SequenceMatcher(None, s, t, autojunk=False).get_opcodes():
316
+ if op == "equal":
317
+ continue
318
+ if op == "delete":
319
+ for k in range(i1, i2):
320
+ edits.append({"start": k, "end": k + 1, "replacement": "",
321
+ "type": _coarse_type([s[k]], [])})
322
+ elif op == "insert":
323
+ edits.append({"start": i1, "end": i1, "replacement": " ".join(t[j1:j2]),
324
+ "type": _coarse_type([], t[j1:j2])})
325
+ else:
326
+ edits.extend(_align_block(s[i1:i2], t[j1:j2], i1))
327
+ return edits
328
+
329
+
330
+ def extract_edits(src: str, hyp: str) -> List[Dict]:
331
+ """Word-level edits taking `src` -> `hyp` as token-span dicts {start,end,replacement,type} into
332
+ src.split(). Uses ERRANT (the alignment the scorer was trained / the MASTER was measured on) when
333
+ available, falling back to a self-contained difflib aligner otherwise."""
334
+ e = _errant_edits(src, hyp)
335
+ if e is not None:
336
+ return e
337
+ return _difflib_edits(src, hyp)
338
+
339
+
340
+ # ------------------------------------------------------------------------------------ the scorer
341
+
342
+ def _resolve_mode(cfg: Dict) -> str:
343
+ if "mode" in cfg:
344
+ return cfg["mode"]
345
+ return "pairwise" if cfg.get("pairwise") else "edited"
346
+
347
+
348
+ class EditScorer(nn.Module):
349
+ """Shared-backbone binary edit scorer: encoder -> mean-pool over edit span(s) -> 2 logits.
350
+ Inference twin of spellchecker.reranker.EditScorer (same state_dict keys, same forward).
351
+ Modes: edited (v1, one span) / pairwise (v2, two encodings) / cross (v3, one joint sequence,
352
+ two pooled spans). `type_feature` appends a learned embedding of the (hash-bucketed) edit type."""
353
+
354
+ TYPE_BUCKETS, TYPE_DIM = 64, 32
355
+
356
+ def __init__(self, encoder_name: str, dropout: float = 0.1, mode: str = "edited",
357
+ type_feature: bool = False, _build_encoder: bool = False):
358
+ super().__init__()
359
+ assert mode in ("edited", "pairwise", "cross"), mode
360
+ self.encoder_name = encoder_name
361
+ self.mode = mode
362
+ self.type_feature = type_feature
363
+ self.encoder, hidden = _backbone(encoder_name, pretrained=_build_encoder)
364
+ self.hidden_size = hidden
365
+ self.dropout = nn.Dropout(dropout)
366
+ feat = hidden * (1 if mode == "edited" else 2)
367
+ if type_feature:
368
+ self.type_emb = nn.Embedding(self.TYPE_BUCKETS, self.TYPE_DIM)
369
+ feat += self.TYPE_DIM
370
+ self.head = nn.Linear(feat, 2)
371
+
372
+ def _pool(self, input_ids, attention_mask, span_mask):
373
+ hidden = _last_hidden(self.encoder, input_ids, attention_mask)
374
+ m = span_mask.unsqueeze(-1).to(hidden.dtype)
375
+ return (hidden * m).sum(1) / m.sum(1).clamp(min=1.0)
376
+
377
+ def forward(self, input_ids, attention_mask, span_mask,
378
+ src_input_ids=None, src_attention_mask=None, src_span_mask=None, type_ids=None):
379
+ if self.mode == "cross":
380
+ hidden = _last_hidden(self.encoder, input_ids, attention_mask)
381
+
382
+ def pool(mask):
383
+ m = mask.unsqueeze(-1).to(hidden.dtype)
384
+ return (hidden * m).sum(1) / m.sum(1).clamp(min=1.0)
385
+ pooled = torch.cat([pool(span_mask), pool(src_span_mask)], dim=-1)
386
+ elif self.mode == "pairwise":
387
+ pooled = torch.cat([self._pool(input_ids, attention_mask, span_mask),
388
+ self._pool(src_input_ids, src_attention_mask, src_span_mask)], dim=-1)
389
+ else:
390
+ pooled = self._pool(input_ids, attention_mask, span_mask)
391
+ if self.type_feature:
392
+ pooled = torch.cat([pooled, self.type_emb(type_ids)], dim=-1)
393
+ return {"logits": self.head(self.dropout(pooled))}
394
+
395
+ @classmethod
396
+ def load(cls, scorer_dir: str, map_location="cpu") -> "EditScorer":
397
+ cfg = json.load(open(os.path.join(scorer_dir, "scorer_config.json")))
398
+ model = cls(encoder_name=cfg["encoder_name"], mode=_resolve_mode(cfg),
399
+ type_feature=cfg.get("type_feature", False), _build_encoder=False)
400
+ sd = torch.load(os.path.join(scorer_dir, "pytorch_model.bin"), map_location=map_location,
401
+ weights_only=True)
402
+ model.load_state_dict(sd)
403
+ model.eval()
404
+ return model
405
+
406
+
407
+ # -------------------------------------------------------------------------- reranking entry point
408
+
409
+ @torch.no_grad()
410
+ def _score(scorer: EditScorer, tokenizer, texts: List[str], cands: List[Tuple[int, Dict]],
411
+ device, batch_size: int = 64, max_len: int = 160) -> List[float]:
412
+ """P(edit correct) for each (sentence_index, edit). Per-mode input construction matches
413
+ spellchecker.reranker.RerankedPredictor._score exactly."""
414
+ mode = scorer.mode
415
+ probs: List[float] = []
416
+ for k in range(0, len(cands), batch_size):
417
+ batch = cands[k:k + batch_size]
418
+ if mode == "cross":
419
+ sep = sep_token(tokenizer)
420
+ items = [build_cross_input(texts[i].split(), e, sep) for i, e in batch]
421
+ ids, mask, span, s_span = encode_cross(tokenizer, items, max(max_len, 320))
422
+ kw = {"input_ids": ids.to(device), "attention_mask": mask.to(device),
423
+ "span_mask": span.to(device), "src_span_mask": s_span.to(device)}
424
+ else:
425
+ items = [build_scorer_input(texts[i].split(), e) for i, e in batch]
426
+ ids, mask, span = encode_candidates(tokenizer, items, max_len)
427
+ kw = {"input_ids": ids.to(device), "attention_mask": mask.to(device),
428
+ "span_mask": span.to(device)}
429
+ if mode == "pairwise":
430
+ s_items = [build_source_input(texts[i].split(), e) for i, e in batch]
431
+ s_ids, s_mask, s_span = encode_candidates(tokenizer, s_items, max_len)
432
+ kw.update(src_input_ids=s_ids.to(device), src_attention_mask=s_mask.to(device),
433
+ src_span_mask=s_span.to(device))
434
+ if scorer.type_feature:
435
+ kw["type_ids"] = torch.tensor([type_bucket(e.get("type", "UNK")) for _, e in batch],
436
+ dtype=torch.long).to(device)
437
+ probs += scorer(**kw)["logits"].softmax(-1)[:, 1].tolist()
438
+ return probs
439
+
440
+
441
+ @torch.no_grad()
442
+ def rerank(scorer: EditScorer, tokenizer, sources: List[str], hyps: List[str], tau: float,
443
+ device, batch_size: int = 64, max_len: int = 160) -> List[str]:
444
+ """Over-generated `hyps` (tagger run at the shipped negative keep_confidence) vs `sources`:
445
+ extract per-edit candidates, score each, keep only P >= tau, re-apply to the source. Pointwise
446
+ acceptance — the shipped behaviour. Returns one corrected string per source."""
447
+ out = list(hyps)
448
+ per_sent: Dict[int, List[Dict]] = {}
449
+ for i, (s, h) in enumerate(zip(sources, hyps)):
450
+ if s == h:
451
+ continue
452
+ edits = extract_edits(s, h)
453
+ out[i] = s # rerankable: rebuild from accepted edits only
454
+ if edits:
455
+ per_sent[i] = edits
456
+ if not per_sent:
457
+ return out
458
+ cands = [(i, e) for i, es in per_sent.items() for e in es]
459
+ probs = _score(scorer, tokenizer, sources, cands, device, batch_size, max_len)
460
+ accepted = defaultdict(list)
461
+ for (i, e), p in zip(cands, probs):
462
+ if p >= tau:
463
+ accepted[i].append(e)
464
+ for i, edits in accepted.items():
465
+ out[i] = " ".join(apply_edits(sources[i].split(), edits))
466
+ return out
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "mask_token": "<|mask|>",
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "pad_token": "<|pad|>",
10
+ "tokenizer_class": "TokenizersBackend"
11
+ }