sasakiy84 commited on
Commit
2d0fc19
·
verified ·
1 Parent(s): 13b918e

ブラウザ対応の軽量版を追加

Browse files

PyTorchとONNX、ブラウザ版ZIP、実行例と評価結果を収録

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE +202 -0
  2. NOTICE.md +9 -0
  3. README.md +60 -0
  4. bibform-lite-web.zip +3 -0
  5. evaluation.json +40 -0
  6. examples/input.jsonl +2 -0
  7. licenses/ONNX-Runtime-MIT.txt +21 -0
  8. licenses/ONNX-Runtime-ThirdPartyNotices.txt +0 -0
  9. onnx/byte-network.onnx +3 -0
  10. onnx/model.json +2425 -0
  11. onnx/role-network.onnx +3 -0
  12. pytorch/byte_architecture.json +6 -0
  13. pytorch/byte_extractor.safetensors +3 -0
  14. pytorch/predict.py +89 -0
  15. pytorch/requirements.txt +5 -0
  16. pytorch/resource_type.json +38 -0
  17. pytorch/resource_type.safetensors +3 -0
  18. pytorch/resource_type_model.py +166 -0
  19. pytorch/resource_type_raw.json +27 -0
  20. pytorch/resource_type_raw.safetensors +3 -0
  21. pytorch/shared/__init__.py +1 -0
  22. pytorch/shared/bibform_trial.py +225 -0
  23. pytorch/shared/bibform_trial_adapters.py +85 -0
  24. pytorch/shared/bibform_trial_model.py +750 -0
  25. pytorch/shared/compact_byte_extractor.py +62 -0
  26. pytorch/shared/compact_character_proxy.py +40 -0
  27. pytorch/shared/compact_edition_endpoint.py +77 -0
  28. pytorch/shared/compact_model_selector.py +105 -0
  29. pytorch/shared/compact_path_ranker.py +139 -0
  30. pytorch/shared/compact_score_blend.py +52 -0
  31. pytorch/shared/compact_title_acceptance.py +41 -0
  32. pytorch/shared/compact_title_pointer.py +112 -0
  33. pytorch/shared/compact_trial_head_storage.py +17 -0
  34. pytorch/shared/compact_version_spans.py +38 -0
  35. pytorch/shared/compact_weight_deltas.py +103 -0
  36. pytorch/shared/count_guided_candidates.py +49 -0
  37. pytorch/shared/count_guided_predictor.py +81 -0
  38. pytorch/shared/csl_spans.py +116 -0
  39. pytorch/shared/dataset_revision.py +79 -0
  40. pytorch/shared/dataset_schema.py +128 -0
  41. pytorch/shared/date_qualifier.py +37 -0
  42. pytorch/shared/doi_volume_prior.py +44 -0
  43. pytorch/shared/field_fragments.py +21 -0
  44. pytorch/shared/field_span_classifier.py +132 -0
  45. pytorch/shared/frozen_character_features.py +40 -0
  46. pytorch/shared/global_field_counts.py +51 -0
  47. pytorch/shared/inference_strategies.py +189 -0
  48. pytorch/shared/kbest_viterbi.py +38 -0
  49. pytorch/shared/name_boundary_prior.py +161 -0
  50. pytorch/shared/name_context_cnn.py +136 -0
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.
NOTICE.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Bibform
2
+
3
+ Copyright 2026 Bibform contributors
4
+
5
+ Bibformの自作部分はApache License 2.0で提供します。
6
+
7
+ ブラウザ版にはONNX Runtime Web 1.31.1を同梱しています。ONNX Runtime WebのMITライセンスと同版の第三者表示は `licenses/` にあります。
8
+
9
+ [ONNX Runtimeの出典](https://github.com/microsoft/onnxruntime/releases/tag/v1.31.1)
README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ja
5
+ - en
6
+ tags:
7
+ - bibliography
8
+ - biblatex
9
+ - local-inference
10
+ ---
11
+
12
+ # Bibform Lite
13
+
14
+ 日本語・英語の参考文献の引用原文から、題名・年・掲載先などの書誌項目、人物・団体、姓・名の文字範囲、著者・編者・訳者などの役割、資料種別を推定します。
15
+
16
+ Bibform extracts citation fields, contributor names and roles, and reference types from Japanese and English reference strings. The PyTorch package runs locally and accepts UTF-8 JSON Lines.
17
+
18
+ PyTorchの推論一式は6.00 MBです。[もう一方のモデル](https://huggingface.co/sasakiy84/bibform)も利用できます。
19
+
20
+ ## ブラウザで使う
21
+
22
+ [ブラウザ版のZIP](bibform-lite-web.zip)を展開し、そのディレクトリを静的ファイルとして配信します。ローカルで試す場合は、展開先で次を実行して `http://127.0.0.1:8000/` を開きます。静的ホストでも同じファイルを使えます。
23
+
24
+ ```bash
25
+ python -m http.server 8000 --bind 127.0.0.1
26
+ ```
27
+
28
+ 初回にモデルと実行エンジンを読み込んだ後は、ブラウザ内で引用の解析、種別の選択、BibLaTeXのプレビューと `.bib` の保存ができます。スコアが0.90未満のときは上位3候補と全種別の一覧から選べます。
29
+
30
+ ONNXモデル一式は5.97 MB、実行エンジンと画面も含む静的配布一式は9.68 MB、ZIPは9.26 MBです。[ONNXと設定](onnx/)、[ブラウザ実装のソース](web-src/)も収録しています。
31
+
32
+ Chromiumで比較した開発128件では、書誌項目・姓名・役割の出力がPyTorch版と128件で一致しました。接続を切った状態での解析とダウンロードも確認しています。
33
+
34
+ ## Pythonで使う
35
+
36
+ Python 3.14の環境で、取得したリポジトリのルートから実行します。
37
+
38
+ ```bash
39
+ python -m pip install -r pytorch/requirements.txt
40
+ python pytorch/predict.py --model pytorch --inputs examples/input.jsonl --output predictions.jsonl --device cpu
41
+ ```
42
+
43
+ 入力は1行に1件の引用を入れたUTF-8のJSONLです。各行に照合用の `id` と引用原文の `text` を指定します。入力例は [examples/input.jsonl](examples/input.jsonl) にあります。
44
+
45
+ 出力の `fields` と `contributors` は、引用原文上の半開区間 `[start, end)` で文字範囲を表します。位置はUnicodeコードポイント単位です。 `resource_type` に元の12種別の首位とスコア、 `resource_type.biblatex` に出力用9種別の候補と自動選択結果が入ります。 `selected` が `null` の場合は候補から種別を選べます。
46
+
47
+ ## 精度と評価条件
48
+
49
+ bibformDatasetTrial v1-quality14の未知書式の開発10,130件を評価しました。抽出完全一致は、書誌項目・人物や団体・姓名の範囲と役割を含みます。種別はBibLaTeX用9種別で採点しました。資料種別のスコアは分類器の出力を合算した値です。
50
+
51
+ | 実行方式 | 抽出完全一致 | 種別正解率 | 抽出と種別の完全一致 |
52
+ | --- | ---: | ---: | ---: |
53
+ | PyTorch | 86.07%(8,719件) | 91.17%(9,236件) | 79.40%(8,043件) |
54
+ | ONNX Runtime CPU | 86.16%(8,728件) | 91.15%(9,234件) | 79.47%(8,050件) |
55
+
56
+ 開発データは実在する書誌メタデータを書式に沿って描画した引用です。公開値はこの開発データでの成績です。短い引用や掲載先が曖昧な引用では、題名の範囲や資料種別を取り違える場合があります。 [集計の詳細](evaluation.json)
57
+
58
+ ## ライセンス
59
+
60
+ Bibformの自作部分には [Apache License 2.0](LICENSE) を適用します。同梱する第三者の配布物とその条件は [NOTICE.md](NOTICE.md) を参照してください。
bibform-lite-web.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c79d7e1aeb4b7baf3922d32bbfde336f009cb0260defbcd48f260e09134b7b1
3
+ size 9255241
evaluation.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "bibformDatasetTrial v1-quality14",
3
+ "split": "unknown_style_development",
4
+ "test_opened": false,
5
+ "pytorch": {
6
+ "extraction": {
7
+ "count": 10130,
8
+ "correct": 8719,
9
+ "accuracy": 0.86071076011846
10
+ },
11
+ "merged_score_9": {
12
+ "count": 10130,
13
+ "correct": 9236,
14
+ "accuracy": 0.9117472852912142
15
+ },
16
+ "joint_9": {
17
+ "count": 10130,
18
+ "correct": 8043,
19
+ "accuracy": 0.7939782823297137
20
+ }
21
+ },
22
+ "onnxruntime_cpu": {
23
+ "count": 10130,
24
+ "same_extraction": 10088,
25
+ "same_12_type": 10123,
26
+ "extraction_exact": 8728,
27
+ "type_9_exact": 9234,
28
+ "joint_9_exact": 8050
29
+ },
30
+ "chromium": {
31
+ "cases": 128,
32
+ "same_python_output": 128,
33
+ "median_ms": 75.19999980926514,
34
+ "p95_ms": 172.30000019073486,
35
+ "download": "reference.bib",
36
+ "assetRequests": 8,
37
+ "offlineInference": true,
38
+ "manualChoices": 3
39
+ }
40
+ }
examples/input.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"id":"example-en","text":"Taylor, J. (2023). Urban rainfall. Example Journal, 4(2), 11–24."}
2
+ {"id":"example-ja","text":"山田太郎(2024)「海辺の植物」架空研究誌、4巻2号、11–24頁。"}
licenses/ONNX-Runtime-MIT.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
licenses/ONNX-Runtime-ThirdPartyNotices.txt ADDED
The diff for this file is too large to render. See raw diff
 
onnx/byte-network.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a953c3ab5826334cb0b47c528291b888179d2666654d74775f7904a210aad03
3
+ size 5831945
onnx/model.json ADDED
@@ -0,0 +1,2425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "outer_labels": [
3
+ "TITLE",
4
+ "CONTAINER_TITLE",
5
+ "DATE",
6
+ "VOLUME",
7
+ "ISSUE",
8
+ "PAGES",
9
+ "ISSUER",
10
+ "LOCATION",
11
+ "DOI",
12
+ "ISBN",
13
+ "URL",
14
+ "EDITION",
15
+ "VERSION",
16
+ "person",
17
+ "organization"
18
+ ],
19
+ "name_labels": [
20
+ "family",
21
+ "given"
22
+ ],
23
+ "fields": [
24
+ "TITLE",
25
+ "CONTAINER_TITLE",
26
+ "DATE",
27
+ "VOLUME",
28
+ "ISSUE",
29
+ "PAGES",
30
+ "ISSUER",
31
+ "DOI",
32
+ "ISBN",
33
+ "URL",
34
+ "EDITION",
35
+ "VERSION"
36
+ ],
37
+ "roles": [
38
+ "author.work",
39
+ "editor.work",
40
+ "translator.work",
41
+ "author.container",
42
+ "editor.container",
43
+ "translator.container"
44
+ ],
45
+ "type_labels": [
46
+ "authored_book",
47
+ "book_chapter",
48
+ "conference_paper",
49
+ "dataset",
50
+ "edited_book",
51
+ "journal_article",
52
+ "proceedings",
53
+ "report",
54
+ "software",
55
+ "thesis",
56
+ "translated_book",
57
+ "web"
58
+ ],
59
+ "export_types": {
60
+ "journal_article": "article",
61
+ "authored_book": "book",
62
+ "edited_book": "collection",
63
+ "translated_book": "book",
64
+ "book_chapter": "incollection",
65
+ "proceedings": "proceedings",
66
+ "conference_paper": "inproceedings",
67
+ "thesis": "thesis",
68
+ "report": "misc",
69
+ "dataset": "misc",
70
+ "software": "misc",
71
+ "web": "online"
72
+ },
73
+ "ngrams": [
74
+ 2,
75
+ 3,
76
+ 4,
77
+ 5
78
+ ],
79
+ "buckets": 32768,
80
+ "states": [
81
+ [
82
+ 0,
83
+ 0,
84
+ 0
85
+ ],
86
+ [
87
+ 1,
88
+ 0,
89
+ 0
90
+ ],
91
+ [
92
+ 2,
93
+ 0,
94
+ 0
95
+ ],
96
+ [
97
+ 3,
98
+ 0,
99
+ 0
100
+ ],
101
+ [
102
+ 4,
103
+ 0,
104
+ 0
105
+ ],
106
+ [
107
+ 5,
108
+ 0,
109
+ 0
110
+ ],
111
+ [
112
+ 6,
113
+ 0,
114
+ 0
115
+ ],
116
+ [
117
+ 7,
118
+ 0,
119
+ 0
120
+ ],
121
+ [
122
+ 8,
123
+ 0,
124
+ 0
125
+ ],
126
+ [
127
+ 9,
128
+ 0,
129
+ 0
130
+ ],
131
+ [
132
+ 10,
133
+ 0,
134
+ 0
135
+ ],
136
+ [
137
+ 11,
138
+ 0,
139
+ 0
140
+ ],
141
+ [
142
+ 12,
143
+ 0,
144
+ 0
145
+ ],
146
+ [
147
+ 13,
148
+ 0,
149
+ 0
150
+ ],
151
+ [
152
+ 14,
153
+ 0,
154
+ 0
155
+ ],
156
+ [
157
+ 15,
158
+ 0,
159
+ 0
160
+ ],
161
+ [
162
+ 16,
163
+ 0,
164
+ 0
165
+ ],
166
+ [
167
+ 17,
168
+ 0,
169
+ 0
170
+ ],
171
+ [
172
+ 18,
173
+ 0,
174
+ 0
175
+ ],
176
+ [
177
+ 19,
178
+ 0,
179
+ 0
180
+ ],
181
+ [
182
+ 20,
183
+ 0,
184
+ 0
185
+ ],
186
+ [
187
+ 21,
188
+ 0,
189
+ 0
190
+ ],
191
+ [
192
+ 22,
193
+ 0,
194
+ 0
195
+ ],
196
+ [
197
+ 23,
198
+ 0,
199
+ 0
200
+ ],
201
+ [
202
+ 24,
203
+ 0,
204
+ 0
205
+ ],
206
+ [
207
+ 25,
208
+ 0,
209
+ 0
210
+ ],
211
+ [
212
+ 26,
213
+ 0,
214
+ 0
215
+ ],
216
+ [
217
+ 29,
218
+ 0,
219
+ 0
220
+ ],
221
+ [
222
+ 30,
223
+ 0,
224
+ 0
225
+ ],
226
+ [
227
+ 27,
228
+ 0,
229
+ 0
230
+ ],
231
+ [
232
+ 27,
233
+ 1,
234
+ 1
235
+ ],
236
+ [
237
+ 27,
238
+ 3,
239
+ 2
240
+ ],
241
+ [
242
+ 28,
243
+ 0,
244
+ 0
245
+ ],
246
+ [
247
+ 28,
248
+ 0,
249
+ 1
250
+ ],
251
+ [
252
+ 28,
253
+ 1,
254
+ 1
255
+ ],
256
+ [
257
+ 28,
258
+ 2,
259
+ 1
260
+ ],
261
+ [
262
+ 28,
263
+ 0,
264
+ 2
265
+ ],
266
+ [
267
+ 28,
268
+ 3,
269
+ 2
270
+ ],
271
+ [
272
+ 28,
273
+ 4,
274
+ 2
275
+ ],
276
+ [
277
+ 28,
278
+ 0,
279
+ 3
280
+ ],
281
+ [
282
+ 28,
283
+ 1,
284
+ 3
285
+ ],
286
+ [
287
+ 28,
288
+ 2,
289
+ 3
290
+ ],
291
+ [
292
+ 28,
293
+ 3,
294
+ 3
295
+ ],
296
+ [
297
+ 28,
298
+ 4,
299
+ 3
300
+ ]
301
+ ],
302
+ "transitions": [
303
+ [
304
+ 0.0,
305
+ 0.0,
306
+ -10000.0,
307
+ 0.0,
308
+ -10000.0,
309
+ 0.0,
310
+ -10000.0,
311
+ 0.0,
312
+ -10000.0,
313
+ 0.0,
314
+ -10000.0,
315
+ 0.0,
316
+ -10000.0,
317
+ 0.0,
318
+ -10000.0,
319
+ 0.0,
320
+ -10000.0,
321
+ 0.0,
322
+ -10000.0,
323
+ 0.0,
324
+ -10000.0,
325
+ 0.0,
326
+ -10000.0,
327
+ 0.0,
328
+ -10000.0,
329
+ 0.0,
330
+ -10000.0,
331
+ 0.0,
332
+ -10000.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ -10000.0,
337
+ -10000.0,
338
+ -10000.0,
339
+ -10000.0,
340
+ -10000.0,
341
+ -10000.0,
342
+ -10000.0,
343
+ -10000.0,
344
+ -10000.0,
345
+ -10000.0,
346
+ -10000.0,
347
+ -10000.0
348
+ ],
349
+ [
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ -10000.0,
355
+ 0.0,
356
+ -10000.0,
357
+ 0.0,
358
+ -10000.0,
359
+ 0.0,
360
+ -10000.0,
361
+ 0.0,
362
+ -10000.0,
363
+ 0.0,
364
+ -10000.0,
365
+ 0.0,
366
+ -10000.0,
367
+ 0.0,
368
+ -10000.0,
369
+ 0.0,
370
+ -10000.0,
371
+ 0.0,
372
+ -10000.0,
373
+ 0.0,
374
+ -10000.0,
375
+ 0.0,
376
+ -10000.0,
377
+ 0.0,
378
+ -10000.0,
379
+ 0.0,
380
+ 0.0,
381
+ 0.0,
382
+ -10000.0,
383
+ -10000.0,
384
+ -10000.0,
385
+ -10000.0,
386
+ -10000.0,
387
+ -10000.0,
388
+ -10000.0,
389
+ -10000.0,
390
+ -10000.0,
391
+ -10000.0,
392
+ -10000.0,
393
+ -10000.0
394
+ ],
395
+ [
396
+ 0.0,
397
+ 0.0,
398
+ 0.0,
399
+ 0.0,
400
+ -10000.0,
401
+ 0.0,
402
+ -10000.0,
403
+ 0.0,
404
+ -10000.0,
405
+ 0.0,
406
+ -10000.0,
407
+ 0.0,
408
+ -10000.0,
409
+ 0.0,
410
+ -10000.0,
411
+ 0.0,
412
+ -10000.0,
413
+ 0.0,
414
+ -10000.0,
415
+ 0.0,
416
+ -10000.0,
417
+ 0.0,
418
+ -10000.0,
419
+ 0.0,
420
+ -10000.0,
421
+ 0.0,
422
+ -10000.0,
423
+ 0.0,
424
+ -10000.0,
425
+ 0.0,
426
+ 0.0,
427
+ 0.0,
428
+ -10000.0,
429
+ -10000.0,
430
+ -10000.0,
431
+ -10000.0,
432
+ -10000.0,
433
+ -10000.0,
434
+ -10000.0,
435
+ -10000.0,
436
+ -10000.0,
437
+ -10000.0,
438
+ -10000.0,
439
+ -10000.0
440
+ ],
441
+ [
442
+ 0.0,
443
+ 0.0,
444
+ -10000.0,
445
+ 0.0,
446
+ 0.0,
447
+ 0.0,
448
+ -10000.0,
449
+ 0.0,
450
+ -10000.0,
451
+ 0.0,
452
+ -10000.0,
453
+ 0.0,
454
+ -10000.0,
455
+ 0.0,
456
+ -10000.0,
457
+ 0.0,
458
+ -10000.0,
459
+ 0.0,
460
+ -10000.0,
461
+ 0.0,
462
+ -10000.0,
463
+ 0.0,
464
+ -10000.0,
465
+ 0.0,
466
+ -10000.0,
467
+ 0.0,
468
+ -10000.0,
469
+ 0.0,
470
+ -10000.0,
471
+ 0.0,
472
+ 0.0,
473
+ 0.0,
474
+ -10000.0,
475
+ -10000.0,
476
+ -10000.0,
477
+ -10000.0,
478
+ -10000.0,
479
+ -10000.0,
480
+ -10000.0,
481
+ -10000.0,
482
+ -10000.0,
483
+ -10000.0,
484
+ -10000.0,
485
+ -10000.0
486
+ ],
487
+ [
488
+ 0.0,
489
+ 0.0,
490
+ -10000.0,
491
+ 0.0,
492
+ 0.0,
493
+ 0.0,
494
+ -10000.0,
495
+ 0.0,
496
+ -10000.0,
497
+ 0.0,
498
+ -10000.0,
499
+ 0.0,
500
+ -10000.0,
501
+ 0.0,
502
+ -10000.0,
503
+ 0.0,
504
+ -10000.0,
505
+ 0.0,
506
+ -10000.0,
507
+ 0.0,
508
+ -10000.0,
509
+ 0.0,
510
+ -10000.0,
511
+ 0.0,
512
+ -10000.0,
513
+ 0.0,
514
+ -10000.0,
515
+ 0.0,
516
+ -10000.0,
517
+ 0.0,
518
+ 0.0,
519
+ 0.0,
520
+ -10000.0,
521
+ -10000.0,
522
+ -10000.0,
523
+ -10000.0,
524
+ -10000.0,
525
+ -10000.0,
526
+ -10000.0,
527
+ -10000.0,
528
+ -10000.0,
529
+ -10000.0,
530
+ -10000.0,
531
+ -10000.0
532
+ ],
533
+ [
534
+ 0.0,
535
+ 0.0,
536
+ -10000.0,
537
+ 0.0,
538
+ -10000.0,
539
+ 0.0,
540
+ 0.0,
541
+ 0.0,
542
+ -10000.0,
543
+ 0.0,
544
+ -10000.0,
545
+ 0.0,
546
+ -10000.0,
547
+ 0.0,
548
+ -10000.0,
549
+ 0.0,
550
+ -10000.0,
551
+ 0.0,
552
+ -10000.0,
553
+ 0.0,
554
+ -10000.0,
555
+ 0.0,
556
+ -10000.0,
557
+ 0.0,
558
+ -10000.0,
559
+ 0.0,
560
+ -10000.0,
561
+ 0.0,
562
+ -10000.0,
563
+ 0.0,
564
+ 0.0,
565
+ 0.0,
566
+ -10000.0,
567
+ -10000.0,
568
+ -10000.0,
569
+ -10000.0,
570
+ -10000.0,
571
+ -10000.0,
572
+ -10000.0,
573
+ -10000.0,
574
+ -10000.0,
575
+ -10000.0,
576
+ -10000.0,
577
+ -10000.0
578
+ ],
579
+ [
580
+ 0.0,
581
+ 0.0,
582
+ -10000.0,
583
+ 0.0,
584
+ -10000.0,
585
+ 0.0,
586
+ 0.0,
587
+ 0.0,
588
+ -10000.0,
589
+ 0.0,
590
+ -10000.0,
591
+ 0.0,
592
+ -10000.0,
593
+ 0.0,
594
+ -10000.0,
595
+ 0.0,
596
+ -10000.0,
597
+ 0.0,
598
+ -10000.0,
599
+ 0.0,
600
+ -10000.0,
601
+ 0.0,
602
+ -10000.0,
603
+ 0.0,
604
+ -10000.0,
605
+ 0.0,
606
+ -10000.0,
607
+ 0.0,
608
+ -10000.0,
609
+ 0.0,
610
+ 0.0,
611
+ 0.0,
612
+ -10000.0,
613
+ -10000.0,
614
+ -10000.0,
615
+ -10000.0,
616
+ -10000.0,
617
+ -10000.0,
618
+ -10000.0,
619
+ -10000.0,
620
+ -10000.0,
621
+ -10000.0,
622
+ -10000.0,
623
+ -10000.0
624
+ ],
625
+ [
626
+ 0.0,
627
+ 0.0,
628
+ -10000.0,
629
+ 0.0,
630
+ -10000.0,
631
+ 0.0,
632
+ -10000.0,
633
+ 0.0,
634
+ 0.0,
635
+ 0.0,
636
+ -10000.0,
637
+ 0.0,
638
+ -10000.0,
639
+ 0.0,
640
+ -10000.0,
641
+ 0.0,
642
+ -10000.0,
643
+ 0.0,
644
+ -10000.0,
645
+ 0.0,
646
+ -10000.0,
647
+ 0.0,
648
+ -10000.0,
649
+ 0.0,
650
+ -10000.0,
651
+ 0.0,
652
+ -10000.0,
653
+ 0.0,
654
+ -10000.0,
655
+ 0.0,
656
+ 0.0,
657
+ 0.0,
658
+ -10000.0,
659
+ -10000.0,
660
+ -10000.0,
661
+ -10000.0,
662
+ -10000.0,
663
+ -10000.0,
664
+ -10000.0,
665
+ -10000.0,
666
+ -10000.0,
667
+ -10000.0,
668
+ -10000.0,
669
+ -10000.0
670
+ ],
671
+ [
672
+ 0.0,
673
+ 0.0,
674
+ -10000.0,
675
+ 0.0,
676
+ -10000.0,
677
+ 0.0,
678
+ -10000.0,
679
+ 0.0,
680
+ 0.0,
681
+ 0.0,
682
+ -10000.0,
683
+ 0.0,
684
+ -10000.0,
685
+ 0.0,
686
+ -10000.0,
687
+ 0.0,
688
+ -10000.0,
689
+ 0.0,
690
+ -10000.0,
691
+ 0.0,
692
+ -10000.0,
693
+ 0.0,
694
+ -10000.0,
695
+ 0.0,
696
+ -10000.0,
697
+ 0.0,
698
+ -10000.0,
699
+ 0.0,
700
+ -10000.0,
701
+ 0.0,
702
+ 0.0,
703
+ 0.0,
704
+ -10000.0,
705
+ -10000.0,
706
+ -10000.0,
707
+ -10000.0,
708
+ -10000.0,
709
+ -10000.0,
710
+ -10000.0,
711
+ -10000.0,
712
+ -10000.0,
713
+ -10000.0,
714
+ -10000.0,
715
+ -10000.0
716
+ ],
717
+ [
718
+ 0.0,
719
+ 0.0,
720
+ -10000.0,
721
+ 0.0,
722
+ -10000.0,
723
+ 0.0,
724
+ -10000.0,
725
+ 0.0,
726
+ -10000.0,
727
+ 0.0,
728
+ 0.0,
729
+ 0.0,
730
+ -10000.0,
731
+ 0.0,
732
+ -10000.0,
733
+ 0.0,
734
+ -10000.0,
735
+ 0.0,
736
+ -10000.0,
737
+ 0.0,
738
+ -10000.0,
739
+ 0.0,
740
+ -10000.0,
741
+ 0.0,
742
+ -10000.0,
743
+ 0.0,
744
+ -10000.0,
745
+ 0.0,
746
+ -10000.0,
747
+ 0.0,
748
+ 0.0,
749
+ 0.0,
750
+ -10000.0,
751
+ -10000.0,
752
+ -10000.0,
753
+ -10000.0,
754
+ -10000.0,
755
+ -10000.0,
756
+ -10000.0,
757
+ -10000.0,
758
+ -10000.0,
759
+ -10000.0,
760
+ -10000.0,
761
+ -10000.0
762
+ ],
763
+ [
764
+ 0.0,
765
+ 0.0,
766
+ -10000.0,
767
+ 0.0,
768
+ -10000.0,
769
+ 0.0,
770
+ -10000.0,
771
+ 0.0,
772
+ -10000.0,
773
+ 0.0,
774
+ 0.0,
775
+ 0.0,
776
+ -10000.0,
777
+ 0.0,
778
+ -10000.0,
779
+ 0.0,
780
+ -10000.0,
781
+ 0.0,
782
+ -10000.0,
783
+ 0.0,
784
+ -10000.0,
785
+ 0.0,
786
+ -10000.0,
787
+ 0.0,
788
+ -10000.0,
789
+ 0.0,
790
+ -10000.0,
791
+ 0.0,
792
+ -10000.0,
793
+ 0.0,
794
+ 0.0,
795
+ 0.0,
796
+ -10000.0,
797
+ -10000.0,
798
+ -10000.0,
799
+ -10000.0,
800
+ -10000.0,
801
+ -10000.0,
802
+ -10000.0,
803
+ -10000.0,
804
+ -10000.0,
805
+ -10000.0,
806
+ -10000.0,
807
+ -10000.0
808
+ ],
809
+ [
810
+ 0.0,
811
+ 0.0,
812
+ -10000.0,
813
+ 0.0,
814
+ -10000.0,
815
+ 0.0,
816
+ -10000.0,
817
+ 0.0,
818
+ -10000.0,
819
+ 0.0,
820
+ -10000.0,
821
+ 0.0,
822
+ 0.0,
823
+ 0.0,
824
+ -10000.0,
825
+ 0.0,
826
+ -10000.0,
827
+ 0.0,
828
+ -10000.0,
829
+ 0.0,
830
+ -10000.0,
831
+ 0.0,
832
+ -10000.0,
833
+ 0.0,
834
+ -10000.0,
835
+ 0.0,
836
+ -10000.0,
837
+ 0.0,
838
+ -10000.0,
839
+ 0.0,
840
+ 0.0,
841
+ 0.0,
842
+ -10000.0,
843
+ -10000.0,
844
+ -10000.0,
845
+ -10000.0,
846
+ -10000.0,
847
+ -10000.0,
848
+ -10000.0,
849
+ -10000.0,
850
+ -10000.0,
851
+ -10000.0,
852
+ -10000.0,
853
+ -10000.0
854
+ ],
855
+ [
856
+ 0.0,
857
+ 0.0,
858
+ -10000.0,
859
+ 0.0,
860
+ -10000.0,
861
+ 0.0,
862
+ -10000.0,
863
+ 0.0,
864
+ -10000.0,
865
+ 0.0,
866
+ -10000.0,
867
+ 0.0,
868
+ 0.0,
869
+ 0.0,
870
+ -10000.0,
871
+ 0.0,
872
+ -10000.0,
873
+ 0.0,
874
+ -10000.0,
875
+ 0.0,
876
+ -10000.0,
877
+ 0.0,
878
+ -10000.0,
879
+ 0.0,
880
+ -10000.0,
881
+ 0.0,
882
+ -10000.0,
883
+ 0.0,
884
+ -10000.0,
885
+ 0.0,
886
+ 0.0,
887
+ 0.0,
888
+ -10000.0,
889
+ -10000.0,
890
+ -10000.0,
891
+ -10000.0,
892
+ -10000.0,
893
+ -10000.0,
894
+ -10000.0,
895
+ -10000.0,
896
+ -10000.0,
897
+ -10000.0,
898
+ -10000.0,
899
+ -10000.0
900
+ ],
901
+ [
902
+ 0.0,
903
+ 0.0,
904
+ -10000.0,
905
+ 0.0,
906
+ -10000.0,
907
+ 0.0,
908
+ -10000.0,
909
+ 0.0,
910
+ -10000.0,
911
+ 0.0,
912
+ -10000.0,
913
+ 0.0,
914
+ -10000.0,
915
+ 0.0,
916
+ 0.0,
917
+ 0.0,
918
+ -10000.0,
919
+ 0.0,
920
+ -10000.0,
921
+ 0.0,
922
+ -10000.0,
923
+ 0.0,
924
+ -10000.0,
925
+ 0.0,
926
+ -10000.0,
927
+ 0.0,
928
+ -10000.0,
929
+ 0.0,
930
+ -10000.0,
931
+ 0.0,
932
+ 0.0,
933
+ 0.0,
934
+ -10000.0,
935
+ -10000.0,
936
+ -10000.0,
937
+ -10000.0,
938
+ -10000.0,
939
+ -10000.0,
940
+ -10000.0,
941
+ -10000.0,
942
+ -10000.0,
943
+ -10000.0,
944
+ -10000.0,
945
+ -10000.0
946
+ ],
947
+ [
948
+ 0.0,
949
+ 0.0,
950
+ -10000.0,
951
+ 0.0,
952
+ -10000.0,
953
+ 0.0,
954
+ -10000.0,
955
+ 0.0,
956
+ -10000.0,
957
+ 0.0,
958
+ -10000.0,
959
+ 0.0,
960
+ -10000.0,
961
+ 0.0,
962
+ 0.0,
963
+ 0.0,
964
+ -10000.0,
965
+ 0.0,
966
+ -10000.0,
967
+ 0.0,
968
+ -10000.0,
969
+ 0.0,
970
+ -10000.0,
971
+ 0.0,
972
+ -10000.0,
973
+ 0.0,
974
+ -10000.0,
975
+ 0.0,
976
+ -10000.0,
977
+ 0.0,
978
+ 0.0,
979
+ 0.0,
980
+ -10000.0,
981
+ -10000.0,
982
+ -10000.0,
983
+ -10000.0,
984
+ -10000.0,
985
+ -10000.0,
986
+ -10000.0,
987
+ -10000.0,
988
+ -10000.0,
989
+ -10000.0,
990
+ -10000.0,
991
+ -10000.0
992
+ ],
993
+ [
994
+ 0.0,
995
+ 0.0,
996
+ -10000.0,
997
+ 0.0,
998
+ -10000.0,
999
+ 0.0,
1000
+ -10000.0,
1001
+ 0.0,
1002
+ -10000.0,
1003
+ 0.0,
1004
+ -10000.0,
1005
+ 0.0,
1006
+ -10000.0,
1007
+ 0.0,
1008
+ -10000.0,
1009
+ 0.0,
1010
+ 0.0,
1011
+ 0.0,
1012
+ -10000.0,
1013
+ 0.0,
1014
+ -10000.0,
1015
+ 0.0,
1016
+ -10000.0,
1017
+ 0.0,
1018
+ -10000.0,
1019
+ 0.0,
1020
+ -10000.0,
1021
+ 0.0,
1022
+ -10000.0,
1023
+ 0.0,
1024
+ 0.0,
1025
+ 0.0,
1026
+ -10000.0,
1027
+ -10000.0,
1028
+ -10000.0,
1029
+ -10000.0,
1030
+ -10000.0,
1031
+ -10000.0,
1032
+ -10000.0,
1033
+ -10000.0,
1034
+ -10000.0,
1035
+ -10000.0,
1036
+ -10000.0,
1037
+ -10000.0
1038
+ ],
1039
+ [
1040
+ 0.0,
1041
+ 0.0,
1042
+ -10000.0,
1043
+ 0.0,
1044
+ -10000.0,
1045
+ 0.0,
1046
+ -10000.0,
1047
+ 0.0,
1048
+ -10000.0,
1049
+ 0.0,
1050
+ -10000.0,
1051
+ 0.0,
1052
+ -10000.0,
1053
+ 0.0,
1054
+ -10000.0,
1055
+ 0.0,
1056
+ 0.0,
1057
+ 0.0,
1058
+ -10000.0,
1059
+ 0.0,
1060
+ -10000.0,
1061
+ 0.0,
1062
+ -10000.0,
1063
+ 0.0,
1064
+ -10000.0,
1065
+ 0.0,
1066
+ -10000.0,
1067
+ 0.0,
1068
+ -10000.0,
1069
+ 0.0,
1070
+ 0.0,
1071
+ 0.0,
1072
+ -10000.0,
1073
+ -10000.0,
1074
+ -10000.0,
1075
+ -10000.0,
1076
+ -10000.0,
1077
+ -10000.0,
1078
+ -10000.0,
1079
+ -10000.0,
1080
+ -10000.0,
1081
+ -10000.0,
1082
+ -10000.0,
1083
+ -10000.0
1084
+ ],
1085
+ [
1086
+ 0.0,
1087
+ 0.0,
1088
+ -10000.0,
1089
+ 0.0,
1090
+ -10000.0,
1091
+ 0.0,
1092
+ -10000.0,
1093
+ 0.0,
1094
+ -10000.0,
1095
+ 0.0,
1096
+ -10000.0,
1097
+ 0.0,
1098
+ -10000.0,
1099
+ 0.0,
1100
+ -10000.0,
1101
+ 0.0,
1102
+ -10000.0,
1103
+ 0.0,
1104
+ 0.0,
1105
+ 0.0,
1106
+ -10000.0,
1107
+ 0.0,
1108
+ -10000.0,
1109
+ 0.0,
1110
+ -10000.0,
1111
+ 0.0,
1112
+ -10000.0,
1113
+ 0.0,
1114
+ -10000.0,
1115
+ 0.0,
1116
+ 0.0,
1117
+ 0.0,
1118
+ -10000.0,
1119
+ -10000.0,
1120
+ -10000.0,
1121
+ -10000.0,
1122
+ -10000.0,
1123
+ -10000.0,
1124
+ -10000.0,
1125
+ -10000.0,
1126
+ -10000.0,
1127
+ -10000.0,
1128
+ -10000.0,
1129
+ -10000.0
1130
+ ],
1131
+ [
1132
+ 0.0,
1133
+ 0.0,
1134
+ -10000.0,
1135
+ 0.0,
1136
+ -10000.0,
1137
+ 0.0,
1138
+ -10000.0,
1139
+ 0.0,
1140
+ -10000.0,
1141
+ 0.0,
1142
+ -10000.0,
1143
+ 0.0,
1144
+ -10000.0,
1145
+ 0.0,
1146
+ -10000.0,
1147
+ 0.0,
1148
+ -10000.0,
1149
+ 0.0,
1150
+ 0.0,
1151
+ 0.0,
1152
+ -10000.0,
1153
+ 0.0,
1154
+ -10000.0,
1155
+ 0.0,
1156
+ -10000.0,
1157
+ 0.0,
1158
+ -10000.0,
1159
+ 0.0,
1160
+ -10000.0,
1161
+ 0.0,
1162
+ 0.0,
1163
+ 0.0,
1164
+ -10000.0,
1165
+ -10000.0,
1166
+ -10000.0,
1167
+ -10000.0,
1168
+ -10000.0,
1169
+ -10000.0,
1170
+ -10000.0,
1171
+ -10000.0,
1172
+ -10000.0,
1173
+ -10000.0,
1174
+ -10000.0,
1175
+ -10000.0
1176
+ ],
1177
+ [
1178
+ 0.0,
1179
+ 0.0,
1180
+ -10000.0,
1181
+ 0.0,
1182
+ -10000.0,
1183
+ 0.0,
1184
+ -10000.0,
1185
+ 0.0,
1186
+ -10000.0,
1187
+ 0.0,
1188
+ -10000.0,
1189
+ 0.0,
1190
+ -10000.0,
1191
+ 0.0,
1192
+ -10000.0,
1193
+ 0.0,
1194
+ -10000.0,
1195
+ 0.0,
1196
+ -10000.0,
1197
+ 0.0,
1198
+ 0.0,
1199
+ 0.0,
1200
+ -10000.0,
1201
+ 0.0,
1202
+ -10000.0,
1203
+ 0.0,
1204
+ -10000.0,
1205
+ 0.0,
1206
+ -10000.0,
1207
+ 0.0,
1208
+ 0.0,
1209
+ 0.0,
1210
+ -10000.0,
1211
+ -10000.0,
1212
+ -10000.0,
1213
+ -10000.0,
1214
+ -10000.0,
1215
+ -10000.0,
1216
+ -10000.0,
1217
+ -10000.0,
1218
+ -10000.0,
1219
+ -10000.0,
1220
+ -10000.0,
1221
+ -10000.0
1222
+ ],
1223
+ [
1224
+ 0.0,
1225
+ 0.0,
1226
+ -10000.0,
1227
+ 0.0,
1228
+ -10000.0,
1229
+ 0.0,
1230
+ -10000.0,
1231
+ 0.0,
1232
+ -10000.0,
1233
+ 0.0,
1234
+ -10000.0,
1235
+ 0.0,
1236
+ -10000.0,
1237
+ 0.0,
1238
+ -10000.0,
1239
+ 0.0,
1240
+ -10000.0,
1241
+ 0.0,
1242
+ -10000.0,
1243
+ 0.0,
1244
+ 0.0,
1245
+ 0.0,
1246
+ -10000.0,
1247
+ 0.0,
1248
+ -10000.0,
1249
+ 0.0,
1250
+ -10000.0,
1251
+ 0.0,
1252
+ -10000.0,
1253
+ 0.0,
1254
+ 0.0,
1255
+ 0.0,
1256
+ -10000.0,
1257
+ -10000.0,
1258
+ -10000.0,
1259
+ -10000.0,
1260
+ -10000.0,
1261
+ -10000.0,
1262
+ -10000.0,
1263
+ -10000.0,
1264
+ -10000.0,
1265
+ -10000.0,
1266
+ -10000.0,
1267
+ -10000.0
1268
+ ],
1269
+ [
1270
+ 0.0,
1271
+ 0.0,
1272
+ -10000.0,
1273
+ 0.0,
1274
+ -10000.0,
1275
+ 0.0,
1276
+ -10000.0,
1277
+ 0.0,
1278
+ -10000.0,
1279
+ 0.0,
1280
+ -10000.0,
1281
+ 0.0,
1282
+ -10000.0,
1283
+ 0.0,
1284
+ -10000.0,
1285
+ 0.0,
1286
+ -10000.0,
1287
+ 0.0,
1288
+ -10000.0,
1289
+ 0.0,
1290
+ -10000.0,
1291
+ 0.0,
1292
+ 0.0,
1293
+ 0.0,
1294
+ -10000.0,
1295
+ 0.0,
1296
+ -10000.0,
1297
+ 0.0,
1298
+ -10000.0,
1299
+ 0.0,
1300
+ 0.0,
1301
+ 0.0,
1302
+ -10000.0,
1303
+ -10000.0,
1304
+ -10000.0,
1305
+ -10000.0,
1306
+ -10000.0,
1307
+ -10000.0,
1308
+ -10000.0,
1309
+ -10000.0,
1310
+ -10000.0,
1311
+ -10000.0,
1312
+ -10000.0,
1313
+ -10000.0
1314
+ ],
1315
+ [
1316
+ 0.0,
1317
+ 0.0,
1318
+ -10000.0,
1319
+ 0.0,
1320
+ -10000.0,
1321
+ 0.0,
1322
+ -10000.0,
1323
+ 0.0,
1324
+ -10000.0,
1325
+ 0.0,
1326
+ -10000.0,
1327
+ 0.0,
1328
+ -10000.0,
1329
+ 0.0,
1330
+ -10000.0,
1331
+ 0.0,
1332
+ -10000.0,
1333
+ 0.0,
1334
+ -10000.0,
1335
+ 0.0,
1336
+ -10000.0,
1337
+ 0.0,
1338
+ 0.0,
1339
+ 0.0,
1340
+ -10000.0,
1341
+ 0.0,
1342
+ -10000.0,
1343
+ 0.0,
1344
+ -10000.0,
1345
+ 0.0,
1346
+ 0.0,
1347
+ 0.0,
1348
+ -10000.0,
1349
+ -10000.0,
1350
+ -10000.0,
1351
+ -10000.0,
1352
+ -10000.0,
1353
+ -10000.0,
1354
+ -10000.0,
1355
+ -10000.0,
1356
+ -10000.0,
1357
+ -10000.0,
1358
+ -10000.0,
1359
+ -10000.0
1360
+ ],
1361
+ [
1362
+ 0.0,
1363
+ 0.0,
1364
+ -10000.0,
1365
+ 0.0,
1366
+ -10000.0,
1367
+ 0.0,
1368
+ -10000.0,
1369
+ 0.0,
1370
+ -10000.0,
1371
+ 0.0,
1372
+ -10000.0,
1373
+ 0.0,
1374
+ -10000.0,
1375
+ 0.0,
1376
+ -10000.0,
1377
+ 0.0,
1378
+ -10000.0,
1379
+ 0.0,
1380
+ -10000.0,
1381
+ 0.0,
1382
+ -10000.0,
1383
+ 0.0,
1384
+ -10000.0,
1385
+ 0.0,
1386
+ 0.0,
1387
+ 0.0,
1388
+ -10000.0,
1389
+ 0.0,
1390
+ -10000.0,
1391
+ 0.0,
1392
+ 0.0,
1393
+ 0.0,
1394
+ -10000.0,
1395
+ -10000.0,
1396
+ -10000.0,
1397
+ -10000.0,
1398
+ -10000.0,
1399
+ -10000.0,
1400
+ -10000.0,
1401
+ -10000.0,
1402
+ -10000.0,
1403
+ -10000.0,
1404
+ -10000.0,
1405
+ -10000.0
1406
+ ],
1407
+ [
1408
+ 0.0,
1409
+ 0.0,
1410
+ -10000.0,
1411
+ 0.0,
1412
+ -10000.0,
1413
+ 0.0,
1414
+ -10000.0,
1415
+ 0.0,
1416
+ -10000.0,
1417
+ 0.0,
1418
+ -10000.0,
1419
+ 0.0,
1420
+ -10000.0,
1421
+ 0.0,
1422
+ -10000.0,
1423
+ 0.0,
1424
+ -10000.0,
1425
+ 0.0,
1426
+ -10000.0,
1427
+ 0.0,
1428
+ -10000.0,
1429
+ 0.0,
1430
+ -10000.0,
1431
+ 0.0,
1432
+ 0.0,
1433
+ 0.0,
1434
+ -10000.0,
1435
+ 0.0,
1436
+ -10000.0,
1437
+ 0.0,
1438
+ 0.0,
1439
+ 0.0,
1440
+ -10000.0,
1441
+ -10000.0,
1442
+ -10000.0,
1443
+ -10000.0,
1444
+ -10000.0,
1445
+ -10000.0,
1446
+ -10000.0,
1447
+ -10000.0,
1448
+ -10000.0,
1449
+ -10000.0,
1450
+ -10000.0,
1451
+ -10000.0
1452
+ ],
1453
+ [
1454
+ 0.0,
1455
+ 0.0,
1456
+ -10000.0,
1457
+ 0.0,
1458
+ -10000.0,
1459
+ 0.0,
1460
+ -10000.0,
1461
+ 0.0,
1462
+ -10000.0,
1463
+ 0.0,
1464
+ -10000.0,
1465
+ 0.0,
1466
+ -10000.0,
1467
+ 0.0,
1468
+ -10000.0,
1469
+ 0.0,
1470
+ -10000.0,
1471
+ 0.0,
1472
+ -10000.0,
1473
+ 0.0,
1474
+ -10000.0,
1475
+ 0.0,
1476
+ -10000.0,
1477
+ 0.0,
1478
+ -10000.0,
1479
+ 0.0,
1480
+ 0.0,
1481
+ 0.0,
1482
+ -10000.0,
1483
+ 0.0,
1484
+ 0.0,
1485
+ 0.0,
1486
+ -10000.0,
1487
+ -10000.0,
1488
+ -10000.0,
1489
+ -10000.0,
1490
+ -10000.0,
1491
+ -10000.0,
1492
+ -10000.0,
1493
+ -10000.0,
1494
+ -10000.0,
1495
+ -10000.0,
1496
+ -10000.0,
1497
+ -10000.0
1498
+ ],
1499
+ [
1500
+ 0.0,
1501
+ 0.0,
1502
+ -10000.0,
1503
+ 0.0,
1504
+ -10000.0,
1505
+ 0.0,
1506
+ -10000.0,
1507
+ 0.0,
1508
+ -10000.0,
1509
+ 0.0,
1510
+ -10000.0,
1511
+ 0.0,
1512
+ -10000.0,
1513
+ 0.0,
1514
+ -10000.0,
1515
+ 0.0,
1516
+ -10000.0,
1517
+ 0.0,
1518
+ -10000.0,
1519
+ 0.0,
1520
+ -10000.0,
1521
+ 0.0,
1522
+ -10000.0,
1523
+ 0.0,
1524
+ -10000.0,
1525
+ 0.0,
1526
+ 0.0,
1527
+ 0.0,
1528
+ -10000.0,
1529
+ 0.0,
1530
+ 0.0,
1531
+ 0.0,
1532
+ -10000.0,
1533
+ -10000.0,
1534
+ -10000.0,
1535
+ -10000.0,
1536
+ -10000.0,
1537
+ -10000.0,
1538
+ -10000.0,
1539
+ -10000.0,
1540
+ -10000.0,
1541
+ -10000.0,
1542
+ -10000.0,
1543
+ -10000.0
1544
+ ],
1545
+ [
1546
+ 0.0,
1547
+ 0.0,
1548
+ -10000.0,
1549
+ 0.0,
1550
+ -10000.0,
1551
+ 0.0,
1552
+ -10000.0,
1553
+ 0.0,
1554
+ -10000.0,
1555
+ 0.0,
1556
+ -10000.0,
1557
+ 0.0,
1558
+ -10000.0,
1559
+ 0.0,
1560
+ -10000.0,
1561
+ 0.0,
1562
+ -10000.0,
1563
+ 0.0,
1564
+ -10000.0,
1565
+ 0.0,
1566
+ -10000.0,
1567
+ 0.0,
1568
+ -10000.0,
1569
+ 0.0,
1570
+ -10000.0,
1571
+ 0.0,
1572
+ -10000.0,
1573
+ 0.0,
1574
+ 0.0,
1575
+ 0.0,
1576
+ 0.0,
1577
+ 0.0,
1578
+ -10000.0,
1579
+ -10000.0,
1580
+ -10000.0,
1581
+ -10000.0,
1582
+ -10000.0,
1583
+ -10000.0,
1584
+ -10000.0,
1585
+ -10000.0,
1586
+ -10000.0,
1587
+ -10000.0,
1588
+ -10000.0,
1589
+ -10000.0
1590
+ ],
1591
+ [
1592
+ 0.0,
1593
+ 0.0,
1594
+ -10000.0,
1595
+ 0.0,
1596
+ -10000.0,
1597
+ 0.0,
1598
+ -10000.0,
1599
+ 0.0,
1600
+ -10000.0,
1601
+ 0.0,
1602
+ -10000.0,
1603
+ 0.0,
1604
+ -10000.0,
1605
+ 0.0,
1606
+ -10000.0,
1607
+ 0.0,
1608
+ -10000.0,
1609
+ 0.0,
1610
+ -10000.0,
1611
+ 0.0,
1612
+ -10000.0,
1613
+ 0.0,
1614
+ -10000.0,
1615
+ 0.0,
1616
+ -10000.0,
1617
+ 0.0,
1618
+ -10000.0,
1619
+ 0.0,
1620
+ 0.0,
1621
+ 0.0,
1622
+ 0.0,
1623
+ 0.0,
1624
+ -10000.0,
1625
+ -10000.0,
1626
+ -10000.0,
1627
+ -10000.0,
1628
+ -10000.0,
1629
+ -10000.0,
1630
+ -10000.0,
1631
+ -10000.0,
1632
+ -10000.0,
1633
+ -10000.0,
1634
+ -10000.0,
1635
+ -10000.0
1636
+ ],
1637
+ [
1638
+ -10000.0,
1639
+ -10000.0,
1640
+ -10000.0,
1641
+ -10000.0,
1642
+ -10000.0,
1643
+ -10000.0,
1644
+ -10000.0,
1645
+ -10000.0,
1646
+ -10000.0,
1647
+ -10000.0,
1648
+ -10000.0,
1649
+ -10000.0,
1650
+ -10000.0,
1651
+ -10000.0,
1652
+ -10000.0,
1653
+ -10000.0,
1654
+ -10000.0,
1655
+ -10000.0,
1656
+ -10000.0,
1657
+ -10000.0,
1658
+ -10000.0,
1659
+ -10000.0,
1660
+ -10000.0,
1661
+ -10000.0,
1662
+ -10000.0,
1663
+ -10000.0,
1664
+ -10000.0,
1665
+ -10000.0,
1666
+ -10000.0,
1667
+ -10000.0,
1668
+ -10000.0,
1669
+ -10000.0,
1670
+ 0.0,
1671
+ -10000.0,
1672
+ 0.0,
1673
+ -10000.0,
1674
+ -10000.0,
1675
+ 0.0,
1676
+ -10000.0,
1677
+ -10000.0,
1678
+ -10000.0,
1679
+ -10000.0,
1680
+ -10000.0,
1681
+ -10000.0
1682
+ ],
1683
+ [
1684
+ 0.0,
1685
+ 0.0,
1686
+ -10000.0,
1687
+ 0.0,
1688
+ -10000.0,
1689
+ 0.0,
1690
+ -10000.0,
1691
+ 0.0,
1692
+ -10000.0,
1693
+ 0.0,
1694
+ -10000.0,
1695
+ 0.0,
1696
+ -10000.0,
1697
+ 0.0,
1698
+ -10000.0,
1699
+ 0.0,
1700
+ -10000.0,
1701
+ 0.0,
1702
+ -10000.0,
1703
+ 0.0,
1704
+ -10000.0,
1705
+ 0.0,
1706
+ -10000.0,
1707
+ 0.0,
1708
+ -10000.0,
1709
+ 0.0,
1710
+ -10000.0,
1711
+ 0.0,
1712
+ -10000.0,
1713
+ 0.0,
1714
+ 0.0,
1715
+ 0.0,
1716
+ -10000.0,
1717
+ 0.0,
1718
+ -10000.0,
1719
+ 0.0,
1720
+ -10000.0,
1721
+ -10000.0,
1722
+ -10000.0,
1723
+ -10000.0,
1724
+ -10000.0,
1725
+ -10000.0,
1726
+ 0.0,
1727
+ -10000.0
1728
+ ],
1729
+ [
1730
+ 0.0,
1731
+ 0.0,
1732
+ -10000.0,
1733
+ 0.0,
1734
+ -10000.0,
1735
+ 0.0,
1736
+ -10000.0,
1737
+ 0.0,
1738
+ -10000.0,
1739
+ 0.0,
1740
+ -10000.0,
1741
+ 0.0,
1742
+ -10000.0,
1743
+ 0.0,
1744
+ -10000.0,
1745
+ 0.0,
1746
+ -10000.0,
1747
+ 0.0,
1748
+ -10000.0,
1749
+ 0.0,
1750
+ -10000.0,
1751
+ 0.0,
1752
+ -10000.0,
1753
+ 0.0,
1754
+ -10000.0,
1755
+ 0.0,
1756
+ -10000.0,
1757
+ 0.0,
1758
+ -10000.0,
1759
+ 0.0,
1760
+ 0.0,
1761
+ 0.0,
1762
+ -10000.0,
1763
+ -10000.0,
1764
+ -10000.0,
1765
+ -10000.0,
1766
+ 0.0,
1767
+ -10000.0,
1768
+ 0.0,
1769
+ -10000.0,
1770
+ 0.0,
1771
+ -10000.0,
1772
+ -10000.0,
1773
+ -10000.0
1774
+ ],
1775
+ [
1776
+ -10000.0,
1777
+ -10000.0,
1778
+ -10000.0,
1779
+ -10000.0,
1780
+ -10000.0,
1781
+ -10000.0,
1782
+ -10000.0,
1783
+ -10000.0,
1784
+ -10000.0,
1785
+ -10000.0,
1786
+ -10000.0,
1787
+ -10000.0,
1788
+ -10000.0,
1789
+ -10000.0,
1790
+ -10000.0,
1791
+ -10000.0,
1792
+ -10000.0,
1793
+ -10000.0,
1794
+ -10000.0,
1795
+ -10000.0,
1796
+ -10000.0,
1797
+ -10000.0,
1798
+ -10000.0,
1799
+ -10000.0,
1800
+ -10000.0,
1801
+ -10000.0,
1802
+ -10000.0,
1803
+ -10000.0,
1804
+ -10000.0,
1805
+ -10000.0,
1806
+ -10000.0,
1807
+ -10000.0,
1808
+ 0.0,
1809
+ -10000.0,
1810
+ 0.0,
1811
+ -10000.0,
1812
+ -10000.0,
1813
+ 0.0,
1814
+ -10000.0,
1815
+ -10000.0,
1816
+ -10000.0,
1817
+ -10000.0,
1818
+ -10000.0,
1819
+ -10000.0
1820
+ ],
1821
+ [
1822
+ 0.0,
1823
+ 0.0,
1824
+ -10000.0,
1825
+ 0.0,
1826
+ -10000.0,
1827
+ 0.0,
1828
+ -10000.0,
1829
+ 0.0,
1830
+ -10000.0,
1831
+ 0.0,
1832
+ -10000.0,
1833
+ 0.0,
1834
+ -10000.0,
1835
+ 0.0,
1836
+ -10000.0,
1837
+ 0.0,
1838
+ -10000.0,
1839
+ 0.0,
1840
+ -10000.0,
1841
+ 0.0,
1842
+ -10000.0,
1843
+ 0.0,
1844
+ -10000.0,
1845
+ 0.0,
1846
+ -10000.0,
1847
+ 0.0,
1848
+ -10000.0,
1849
+ 0.0,
1850
+ -10000.0,
1851
+ 0.0,
1852
+ 0.0,
1853
+ 0.0,
1854
+ -10000.0,
1855
+ 0.0,
1856
+ -10000.0,
1857
+ -10000.0,
1858
+ -10000.0,
1859
+ -10000.0,
1860
+ -10000.0,
1861
+ -10000.0,
1862
+ -10000.0,
1863
+ -10000.0,
1864
+ 0.0,
1865
+ -10000.0
1866
+ ],
1867
+ [
1868
+ 0.0,
1869
+ 0.0,
1870
+ -10000.0,
1871
+ 0.0,
1872
+ -10000.0,
1873
+ 0.0,
1874
+ -10000.0,
1875
+ 0.0,
1876
+ -10000.0,
1877
+ 0.0,
1878
+ -10000.0,
1879
+ 0.0,
1880
+ -10000.0,
1881
+ 0.0,
1882
+ -10000.0,
1883
+ 0.0,
1884
+ -10000.0,
1885
+ 0.0,
1886
+ -10000.0,
1887
+ 0.0,
1888
+ -10000.0,
1889
+ 0.0,
1890
+ -10000.0,
1891
+ 0.0,
1892
+ -10000.0,
1893
+ 0.0,
1894
+ -10000.0,
1895
+ 0.0,
1896
+ -10000.0,
1897
+ 0.0,
1898
+ 0.0,
1899
+ 0.0,
1900
+ -10000.0,
1901
+ 0.0,
1902
+ -10000.0,
1903
+ 0.0,
1904
+ -10000.0,
1905
+ -10000.0,
1906
+ -10000.0,
1907
+ -10000.0,
1908
+ -10000.0,
1909
+ -10000.0,
1910
+ 0.0,
1911
+ -10000.0
1912
+ ],
1913
+ [
1914
+ 0.0,
1915
+ 0.0,
1916
+ -10000.0,
1917
+ 0.0,
1918
+ -10000.0,
1919
+ 0.0,
1920
+ -10000.0,
1921
+ 0.0,
1922
+ -10000.0,
1923
+ 0.0,
1924
+ -10000.0,
1925
+ 0.0,
1926
+ -10000.0,
1927
+ 0.0,
1928
+ -10000.0,
1929
+ 0.0,
1930
+ -10000.0,
1931
+ 0.0,
1932
+ -10000.0,
1933
+ 0.0,
1934
+ -10000.0,
1935
+ 0.0,
1936
+ -10000.0,
1937
+ 0.0,
1938
+ -10000.0,
1939
+ 0.0,
1940
+ -10000.0,
1941
+ 0.0,
1942
+ -10000.0,
1943
+ 0.0,
1944
+ 0.0,
1945
+ 0.0,
1946
+ -10000.0,
1947
+ 0.0,
1948
+ -10000.0,
1949
+ 0.0,
1950
+ -10000.0,
1951
+ -10000.0,
1952
+ -10000.0,
1953
+ -10000.0,
1954
+ -10000.0,
1955
+ -10000.0,
1956
+ 0.0,
1957
+ -10000.0
1958
+ ],
1959
+ [
1960
+ 0.0,
1961
+ 0.0,
1962
+ -10000.0,
1963
+ 0.0,
1964
+ -10000.0,
1965
+ 0.0,
1966
+ -10000.0,
1967
+ 0.0,
1968
+ -10000.0,
1969
+ 0.0,
1970
+ -10000.0,
1971
+ 0.0,
1972
+ -10000.0,
1973
+ 0.0,
1974
+ -10000.0,
1975
+ 0.0,
1976
+ -10000.0,
1977
+ 0.0,
1978
+ -10000.0,
1979
+ 0.0,
1980
+ -10000.0,
1981
+ 0.0,
1982
+ -10000.0,
1983
+ 0.0,
1984
+ -10000.0,
1985
+ 0.0,
1986
+ -10000.0,
1987
+ 0.0,
1988
+ -10000.0,
1989
+ 0.0,
1990
+ 0.0,
1991
+ 0.0,
1992
+ -10000.0,
1993
+ -10000.0,
1994
+ -10000.0,
1995
+ -10000.0,
1996
+ 0.0,
1997
+ -10000.0,
1998
+ -10000.0,
1999
+ -10000.0,
2000
+ 0.0,
2001
+ -10000.0,
2002
+ -10000.0,
2003
+ -10000.0
2004
+ ],
2005
+ [
2006
+ 0.0,
2007
+ 0.0,
2008
+ -10000.0,
2009
+ 0.0,
2010
+ -10000.0,
2011
+ 0.0,
2012
+ -10000.0,
2013
+ 0.0,
2014
+ -10000.0,
2015
+ 0.0,
2016
+ -10000.0,
2017
+ 0.0,
2018
+ -10000.0,
2019
+ 0.0,
2020
+ -10000.0,
2021
+ 0.0,
2022
+ -10000.0,
2023
+ 0.0,
2024
+ -10000.0,
2025
+ 0.0,
2026
+ -10000.0,
2027
+ 0.0,
2028
+ -10000.0,
2029
+ 0.0,
2030
+ -10000.0,
2031
+ 0.0,
2032
+ -10000.0,
2033
+ 0.0,
2034
+ -10000.0,
2035
+ 0.0,
2036
+ 0.0,
2037
+ 0.0,
2038
+ -10000.0,
2039
+ -10000.0,
2040
+ -10000.0,
2041
+ -10000.0,
2042
+ 0.0,
2043
+ -10000.0,
2044
+ 0.0,
2045
+ -10000.0,
2046
+ 0.0,
2047
+ -10000.0,
2048
+ -10000.0,
2049
+ -10000.0
2050
+ ],
2051
+ [
2052
+ 0.0,
2053
+ 0.0,
2054
+ -10000.0,
2055
+ 0.0,
2056
+ -10000.0,
2057
+ 0.0,
2058
+ -10000.0,
2059
+ 0.0,
2060
+ -10000.0,
2061
+ 0.0,
2062
+ -10000.0,
2063
+ 0.0,
2064
+ -10000.0,
2065
+ 0.0,
2066
+ -10000.0,
2067
+ 0.0,
2068
+ -10000.0,
2069
+ 0.0,
2070
+ -10000.0,
2071
+ 0.0,
2072
+ -10000.0,
2073
+ 0.0,
2074
+ -10000.0,
2075
+ 0.0,
2076
+ -10000.0,
2077
+ 0.0,
2078
+ -10000.0,
2079
+ 0.0,
2080
+ -10000.0,
2081
+ 0.0,
2082
+ 0.0,
2083
+ 0.0,
2084
+ -10000.0,
2085
+ -10000.0,
2086
+ -10000.0,
2087
+ -10000.0,
2088
+ 0.0,
2089
+ -10000.0,
2090
+ 0.0,
2091
+ -10000.0,
2092
+ 0.0,
2093
+ -10000.0,
2094
+ -10000.0,
2095
+ -10000.0
2096
+ ],
2097
+ [
2098
+ 0.0,
2099
+ 0.0,
2100
+ -10000.0,
2101
+ 0.0,
2102
+ -10000.0,
2103
+ 0.0,
2104
+ -10000.0,
2105
+ 0.0,
2106
+ -10000.0,
2107
+ 0.0,
2108
+ -10000.0,
2109
+ 0.0,
2110
+ -10000.0,
2111
+ 0.0,
2112
+ -10000.0,
2113
+ 0.0,
2114
+ -10000.0,
2115
+ 0.0,
2116
+ -10000.0,
2117
+ 0.0,
2118
+ -10000.0,
2119
+ 0.0,
2120
+ -10000.0,
2121
+ 0.0,
2122
+ -10000.0,
2123
+ 0.0,
2124
+ -10000.0,
2125
+ 0.0,
2126
+ -10000.0,
2127
+ 0.0,
2128
+ 0.0,
2129
+ 0.0,
2130
+ -10000.0,
2131
+ -10000.0,
2132
+ -10000.0,
2133
+ -10000.0,
2134
+ -10000.0,
2135
+ -10000.0,
2136
+ -10000.0,
2137
+ 0.0,
2138
+ -10000.0,
2139
+ -10000.0,
2140
+ -10000.0,
2141
+ -10000.0
2142
+ ],
2143
+ [
2144
+ 0.0,
2145
+ 0.0,
2146
+ -10000.0,
2147
+ 0.0,
2148
+ -10000.0,
2149
+ 0.0,
2150
+ -10000.0,
2151
+ 0.0,
2152
+ -10000.0,
2153
+ 0.0,
2154
+ -10000.0,
2155
+ 0.0,
2156
+ -10000.0,
2157
+ 0.0,
2158
+ -10000.0,
2159
+ 0.0,
2160
+ -10000.0,
2161
+ 0.0,
2162
+ -10000.0,
2163
+ 0.0,
2164
+ -10000.0,
2165
+ 0.0,
2166
+ -10000.0,
2167
+ 0.0,
2168
+ -10000.0,
2169
+ 0.0,
2170
+ -10000.0,
2171
+ 0.0,
2172
+ -10000.0,
2173
+ 0.0,
2174
+ 0.0,
2175
+ 0.0,
2176
+ -10000.0,
2177
+ -10000.0,
2178
+ -10000.0,
2179
+ -10000.0,
2180
+ -10000.0,
2181
+ -10000.0,
2182
+ -10000.0,
2183
+ 0.0,
2184
+ -10000.0,
2185
+ 0.0,
2186
+ -10000.0,
2187
+ -10000.0
2188
+ ],
2189
+ [
2190
+ 0.0,
2191
+ 0.0,
2192
+ -10000.0,
2193
+ 0.0,
2194
+ -10000.0,
2195
+ 0.0,
2196
+ -10000.0,
2197
+ 0.0,
2198
+ -10000.0,
2199
+ 0.0,
2200
+ -10000.0,
2201
+ 0.0,
2202
+ -10000.0,
2203
+ 0.0,
2204
+ -10000.0,
2205
+ 0.0,
2206
+ -10000.0,
2207
+ 0.0,
2208
+ -10000.0,
2209
+ 0.0,
2210
+ -10000.0,
2211
+ 0.0,
2212
+ -10000.0,
2213
+ 0.0,
2214
+ -10000.0,
2215
+ 0.0,
2216
+ -10000.0,
2217
+ 0.0,
2218
+ -10000.0,
2219
+ 0.0,
2220
+ 0.0,
2221
+ 0.0,
2222
+ -10000.0,
2223
+ -10000.0,
2224
+ -10000.0,
2225
+ -10000.0,
2226
+ -10000.0,
2227
+ -10000.0,
2228
+ -10000.0,
2229
+ 0.0,
2230
+ -10000.0,
2231
+ 0.0,
2232
+ -10000.0,
2233
+ -10000.0
2234
+ ],
2235
+ [
2236
+ 0.0,
2237
+ 0.0,
2238
+ -10000.0,
2239
+ 0.0,
2240
+ -10000.0,
2241
+ 0.0,
2242
+ -10000.0,
2243
+ 0.0,
2244
+ -10000.0,
2245
+ 0.0,
2246
+ -10000.0,
2247
+ 0.0,
2248
+ -10000.0,
2249
+ 0.0,
2250
+ -10000.0,
2251
+ 0.0,
2252
+ -10000.0,
2253
+ 0.0,
2254
+ -10000.0,
2255
+ 0.0,
2256
+ -10000.0,
2257
+ 0.0,
2258
+ -10000.0,
2259
+ 0.0,
2260
+ -10000.0,
2261
+ 0.0,
2262
+ -10000.0,
2263
+ 0.0,
2264
+ -10000.0,
2265
+ 0.0,
2266
+ 0.0,
2267
+ 0.0,
2268
+ -10000.0,
2269
+ -10000.0,
2270
+ -10000.0,
2271
+ -10000.0,
2272
+ -10000.0,
2273
+ -10000.0,
2274
+ -10000.0,
2275
+ 0.0,
2276
+ -10000.0,
2277
+ -10000.0,
2278
+ -10000.0,
2279
+ 0.0
2280
+ ],
2281
+ [
2282
+ 0.0,
2283
+ 0.0,
2284
+ -10000.0,
2285
+ 0.0,
2286
+ -10000.0,
2287
+ 0.0,
2288
+ -10000.0,
2289
+ 0.0,
2290
+ -10000.0,
2291
+ 0.0,
2292
+ -10000.0,
2293
+ 0.0,
2294
+ -10000.0,
2295
+ 0.0,
2296
+ -10000.0,
2297
+ 0.0,
2298
+ -10000.0,
2299
+ 0.0,
2300
+ -10000.0,
2301
+ 0.0,
2302
+ -10000.0,
2303
+ 0.0,
2304
+ -10000.0,
2305
+ 0.0,
2306
+ -10000.0,
2307
+ 0.0,
2308
+ -10000.0,
2309
+ 0.0,
2310
+ -10000.0,
2311
+ 0.0,
2312
+ 0.0,
2313
+ 0.0,
2314
+ -10000.0,
2315
+ -10000.0,
2316
+ -10000.0,
2317
+ -10000.0,
2318
+ -10000.0,
2319
+ -10000.0,
2320
+ -10000.0,
2321
+ 0.0,
2322
+ -10000.0,
2323
+ -10000.0,
2324
+ -10000.0,
2325
+ 0.0
2326
+ ]
2327
+ ],
2328
+ "start": [
2329
+ 0.0,
2330
+ 0.0,
2331
+ -10000.0,
2332
+ 0.0,
2333
+ -10000.0,
2334
+ 0.0,
2335
+ -10000.0,
2336
+ 0.0,
2337
+ -10000.0,
2338
+ 0.0,
2339
+ -10000.0,
2340
+ 0.0,
2341
+ -10000.0,
2342
+ 0.0,
2343
+ -10000.0,
2344
+ 0.0,
2345
+ -10000.0,
2346
+ 0.0,
2347
+ -10000.0,
2348
+ 0.0,
2349
+ -10000.0,
2350
+ 0.0,
2351
+ -10000.0,
2352
+ 0.0,
2353
+ -10000.0,
2354
+ 0.0,
2355
+ -10000.0,
2356
+ 0.0,
2357
+ -10000.0,
2358
+ 0.0,
2359
+ 0.0,
2360
+ 0.0,
2361
+ -10000.0,
2362
+ -10000.0,
2363
+ -10000.0,
2364
+ -10000.0,
2365
+ -10000.0,
2366
+ -10000.0,
2367
+ -10000.0,
2368
+ -10000.0,
2369
+ -10000.0,
2370
+ -10000.0,
2371
+ -10000.0,
2372
+ -10000.0
2373
+ ],
2374
+ "end": [
2375
+ 0.0,
2376
+ 0.0,
2377
+ 0.0,
2378
+ 0.0,
2379
+ 0.0,
2380
+ 0.0,
2381
+ 0.0,
2382
+ 0.0,
2383
+ 0.0,
2384
+ 0.0,
2385
+ 0.0,
2386
+ 0.0,
2387
+ 0.0,
2388
+ 0.0,
2389
+ 0.0,
2390
+ 0.0,
2391
+ 0.0,
2392
+ 0.0,
2393
+ 0.0,
2394
+ 0.0,
2395
+ 0.0,
2396
+ 0.0,
2397
+ 0.0,
2398
+ 0.0,
2399
+ 0.0,
2400
+ 0.0,
2401
+ 0.0,
2402
+ 0.0,
2403
+ 0.0,
2404
+ -10000.0,
2405
+ 0.0,
2406
+ 0.0,
2407
+ -10000.0,
2408
+ 0.0,
2409
+ 0.0,
2410
+ 0.0,
2411
+ 0.0,
2412
+ 0.0,
2413
+ 0.0,
2414
+ 0.0,
2415
+ 0.0,
2416
+ 0.0,
2417
+ 0.0,
2418
+ 0.0
2419
+ ],
2420
+ "source_inventory_sha256": "0d4b06f98a343f20adbdeca8499680e050cd7c70bd884b1fbf6a03ccdb6d6188",
2421
+ "packed_initializers": {
2422
+ "byte": 205,
2423
+ "role": 7
2424
+ }
2425
+ }
onnx/role-network.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:029d9fde693486dd86c24f5031d2223e217e12e2c03a864a5db1f1440ff2fa97
3
+ size 110656
pytorch/byte_architecture.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "width": 192,
3
+ "attention_layers": 14,
4
+ "parameters": 4656225,
5
+ "weights_format": "int8"
6
+ }
pytorch/byte_extractor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eac58cb50520d169ca5f8349c9ed058b2b91ff8c35452ec0eae56c74b481e2c9
3
+ size 4800240
pytorch/predict.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the independent byte extractor in a standalone package."""
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from safetensors.torch import load_file
8
+ import torch
9
+ from resource_type_model import ResourceTypeOutput, TypeFieldCountEvidence, pool_context
10
+
11
+ from shared.compact_byte_extractor import CompactByteExtractor
12
+ from shared.weight_storage import decode_int8_weights
13
+
14
+
15
+ def predict(model,rows,device,batch_size,classifier):
16
+ ordered = sorted(rows,key=lambda row:len(row['text']))
17
+ outputs,position = {},0
18
+ while position<len(ordered):
19
+ end = position+1
20
+ while end<len(ordered) and end-position<batch_size and (end-position+1)*len(ordered[end]['text'])**2<=1_400_000:
21
+ end += 1
22
+ raw = ordered[position:end]
23
+ context = []
24
+ if classifier.uses_context:
25
+ lengths = torch.tensor([len(row['text']) for row in raw], device=device)
26
+
27
+ def capture(_module, inputs, logits):
28
+ context.append(pool_context(inputs[0], lengths, logits))
29
+ if classifier.field_scale:
30
+ from shared.bibform_trial import FIELDS
31
+ from shared.span_tagger import OUTER_NAMES
32
+ starts = [1 + 2 * OUTER_NAMES.index(label) for label in FIELDS]
33
+ updated = logits.clone()
34
+ updated[:, :, starts] += classifier.field_evidence(context[0], len(FIELDS))[:, None, :]
35
+ return updated
36
+
37
+ hook = model.head.outer.register_forward_hook(capture)
38
+ try:
39
+ extracted = model.predict(raw, device)
40
+ finally:
41
+ hook.remove()
42
+ if len(context) != 1:
43
+ raise ValueError('expected_one_resource_type_feature_batch')
44
+ else:
45
+ extracted = model.predict(raw, device)
46
+ typed = classifier.attach(raw, extracted, context[0] if context else None)
47
+ outputs.update((row['id'],row) for row in typed)
48
+ position = end
49
+ return [outputs[row['id']] for row in rows]
50
+
51
+
52
+ def main():
53
+ parser = argparse.ArgumentParser(description=__doc__)
54
+ parser.add_argument('--model',type=Path,required=True)
55
+ parser.add_argument('--inputs',type=Path,required=True)
56
+ parser.add_argument('--output',type=Path,required=True)
57
+ parser.add_argument('--device',choices=('cpu','cuda'),default='cuda' if torch.cuda.is_available() else 'cpu')
58
+ parser.add_argument('--batch-size',type=int,default=48)
59
+ args = parser.parse_args()
60
+ if args.batch_size<1:
61
+ parser.error('positive batch size required')
62
+ torch.set_num_threads(1)
63
+ torch.backends.cuda.matmul.allow_tf32 = False
64
+ rows = [json.loads(line) for line in args.inputs.read_text().splitlines()]
65
+ if any(set(row)!={'id','text'} or not isinstance(row['id'],str) or
66
+ not isinstance(row['text'],str) or not row['text'] for row in rows):
67
+ raise ValueError('only_nonempty_original_id_and_text_are_accepted')
68
+ if len({row['id'] for row in rows})!=len(rows):
69
+ raise ValueError('duplicate_input_id')
70
+ config_path = args.model/'byte_architecture.json'
71
+ config = {}
72
+ if config_path.exists():
73
+ config = json.loads(config_path.read_text())
74
+ model = CompactByteExtractor(width=config['width'],depth=config['attention_layers'])
75
+ else:
76
+ model = CompactByteExtractor()
77
+ model.to(args.device).eval()
78
+ weights = load_file(args.model/'byte_extractor.safetensors')
79
+ if config.get('weights_format')=='int8':
80
+ weights = decode_int8_weights(weights)
81
+ model.load_state_dict(weights)
82
+ classifier = ResourceTypeOutput(args.model)
83
+ results = predict(model,rows,args.device,args.batch_size,classifier)
84
+ args.output.parent.mkdir(parents=True,exist_ok=True)
85
+ args.output.write_text(''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in results))
86
+
87
+
88
+ if __name__=='__main__':
89
+ main()
pytorch/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ transformers==4.57.6
3
+ safetensors==0.8.0
4
+ sentencepiece==0.2.3
5
+ protobuf==7.36.2
pytorch/resource_type.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "joint_fields",
3
+ "labels": [
4
+ "authored_book",
5
+ "book_chapter",
6
+ "conference_paper",
7
+ "dataset",
8
+ "edited_book",
9
+ "journal_article",
10
+ "proceedings",
11
+ "report",
12
+ "software",
13
+ "thesis",
14
+ "translated_book",
15
+ "web"
16
+ ],
17
+ "width": 128,
18
+ "context_width": 415,
19
+ "field_outputs": 18,
20
+ "field_weight": 0.4,
21
+ "work_weight": 0.35,
22
+ "cache_sha256": "6b4c4d3df309b0da81ae92e026b62c1efbdc96e7da6123f6acbedf9a7394b0e5",
23
+ "raw_weight": 0.35,
24
+ "biblatex_type_map": {
25
+ "journal_article": "article",
26
+ "authored_book": "book",
27
+ "edited_book": "collection",
28
+ "translated_book": "book",
29
+ "book_chapter": "incollection",
30
+ "proceedings": "proceedings",
31
+ "conference_paper": "inproceedings",
32
+ "thesis": "thesis",
33
+ "report": "misc",
34
+ "dataset": "misc",
35
+ "software": "misc",
36
+ "web": "online"
37
+ }
38
+ }
pytorch/resource_type.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7054de1a8f6fa9dd88b06e46995bda2471a2e43933624c2aa1b4d1e464a9db46
3
+ size 117544
pytorch/resource_type_model.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classify a citation from its original characters with a bounded weight table."""
2
+
3
+ import math
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ from safetensors.torch import load_file
9
+ import torch
10
+ from torch import Tensor, nn
11
+
12
+
13
+ def character_features(text: str, ngrams: tuple[int, ...], buckets: int) -> np.ndarray:
14
+ points = np.fromiter((ord(char) + 3 for char in text), dtype=np.uint32, count=len(text))
15
+ points = np.concatenate((np.array([1], dtype=np.uint32), points, np.array([2], dtype=np.uint32)))
16
+ features = []
17
+ for n in ngrams:
18
+ size = len(points) - n + 1
19
+ if size <= 0:
20
+ continue
21
+ hashes = np.full(size, n * 4099, dtype=np.uint32)
22
+ for step in range(n):
23
+ hashes = (hashes ^ points[step:step + size]) * np.uint32(16777619)
24
+ hashes ^= hashes >> 16
25
+ features.append(hashes % buckets)
26
+ return np.unique(np.concatenate(features)) if features else np.zeros(1, dtype=np.uint32)
27
+
28
+
29
+ def pack_features(rows: list[np.ndarray]) -> tuple[Tensor, Tensor, Tensor]:
30
+ lengths = np.fromiter((len(row) for row in rows), dtype=np.int64, count=len(rows))
31
+ offsets = np.concatenate((np.zeros(1, dtype=np.int64), np.cumsum(lengths)))
32
+ return (torch.from_numpy(np.concatenate(rows).astype(np.int64)), torch.from_numpy(offsets),
33
+ torch.from_numpy(lengths.astype(np.float32)).rsqrt().unsqueeze(-1))
34
+
35
+
36
+ class ResourceTypeClassifier(nn.Module):
37
+ def __init__(self, classes: int, buckets: int, width: int, context_width: int = 0) -> None:
38
+ super().__init__()
39
+ self.table = nn.EmbeddingBag(buckets, width, mode='sum', sparse=True, include_last_offset=True)
40
+ nn.init.normal_(self.table.weight, std=1. / math.sqrt(width))
41
+ self.output = nn.Linear(width + context_width, classes)
42
+
43
+ def forward(self, packed: tuple[Tensor, Tensor, Tensor], context: Tensor | None = None) -> Tensor:
44
+ indices, offsets, scale = packed
45
+ summary = self.table(indices, offsets) * scale
46
+ if context is not None:
47
+ summary = torch.cat((summary, context), dim=-1)
48
+ return self.output(summary)
49
+
50
+
51
+ def output_type(scores: Tensor, labels: list[str]) -> list[dict]:
52
+ probabilities = scores.softmax(-1)
53
+ confidence, indices = probabilities.max(-1)
54
+ return [{'label': labels[index], 'confidence': float(value)}
55
+ for index, value in zip(indices.tolist(), confidence.tolist(), strict=True)]
56
+
57
+
58
+ def pool_context(hidden: Tensor, lengths: Tensor, outer_logits: Tensor) -> Tensor:
59
+ valid = torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None]
60
+ mask = valid.unsqueeze(-1)
61
+ mean = (hidden * mask).sum(1) / lengths[:, None]
62
+ maximum = hidden.masked_fill(~mask, -torch.inf).amax(1)
63
+ mass = (outer_logits.float().softmax(-1) * mask).sum(1).log1p()
64
+ return torch.cat((mean, maximum, mass), dim=-1).float()
65
+
66
+
67
+ class ContextResourceClassifier(nn.Module):
68
+ def __init__(self, classes: int, inputs: int, width: int, fields: int) -> None:
69
+ super().__init__()
70
+ self.register_buffer('center', torch.zeros(inputs))
71
+ self.register_buffer('spread', torch.ones(inputs))
72
+ self.features = nn.Sequential(nn.Linear(inputs, width), nn.GELU(), nn.Dropout(.15))
73
+ self.kind = nn.Linear(width, classes)
74
+ self.fields = nn.Linear(width, fields) if fields else None
75
+ self.kind_from_fields = nn.Linear(fields, classes, bias=False) if fields else None
76
+ self.fields_from_kind = nn.Linear(classes, fields, bias=False) if fields else None
77
+
78
+ def forward(self, context: Tensor) -> tuple[Tensor, Tensor | None]:
79
+ hidden = self.features(((context - self.center) / self.spread).clamp(-12., 12.))
80
+ kind = self.kind(hidden)
81
+ if self.fields is None:
82
+ return kind, None
83
+ fields = self.fields(hidden)
84
+ kind = kind + self.kind_from_fields(fields.sigmoid())
85
+ return kind, fields + self.fields_from_kind(kind.softmax(-1))
86
+
87
+
88
+ class ResourceTypeOutput:
89
+ def __init__(self, folder: Path) -> None:
90
+ spec = json.loads((folder / 'resource_type.json').read_text())
91
+ self.labels = spec['labels']
92
+ self.biblatex_type_map = spec['biblatex_type_map']
93
+ self.temperature = spec.get('temperature', 1.)
94
+ self.threshold = spec.get('abstention_threshold', 0.)
95
+ self.field_scale = spec.get('field_scale', 0.)
96
+ self.raw_weight = spec.get('raw_weight', 0.)
97
+ if spec.get('context_width'):
98
+ self.uses_context = True
99
+ self.model = ContextResourceClassifier(len(self.labels), spec['context_width'], spec['width'],
100
+ spec.get('field_outputs', 0))
101
+ else:
102
+ self.uses_context = False
103
+ self.model = ResourceTypeClassifier(len(self.labels), spec['buckets'], spec['width'])
104
+ self.ngrams, self.buckets = tuple(spec['ngrams']), spec['buckets']
105
+ self.model.load_state_dict(load_file(folder / 'resource_type.safetensors'))
106
+ self.model.eval()
107
+ if self.raw_weight:
108
+ raw = json.loads((folder / 'resource_type_raw.json').read_text())
109
+ if raw['labels'] != self.labels or not self.uses_context:
110
+ raise ValueError('resource_type_ensemble_labels_changed')
111
+ self.raw_model = ResourceTypeClassifier(len(self.labels), raw['buckets'], raw['width'])
112
+ self.raw_model.load_state_dict(load_file(folder / 'resource_type_raw.safetensors'))
113
+ self.raw_model.eval()
114
+ self.raw_ngrams, self.raw_buckets = tuple(raw['ngrams']), raw['buckets']
115
+ if self.field_scale and not spec.get('field_outputs'):
116
+ raise ValueError('resource_type_field_scores_missing')
117
+
118
+ @torch.inference_mode()
119
+ def field_evidence(self, context: Tensor, labels: int) -> Tensor:
120
+ fields = self.model(context.half().float().cpu())[1]
121
+ return fields[:, :labels].tanh().to(context.device) * self.field_scale
122
+
123
+ @torch.inference_mode()
124
+ def attach(self, inputs: list[dict], predictions: list[dict], context: Tensor | None = None) -> list[dict]:
125
+ if self.uses_context:
126
+ if context is None or len(context) != len(inputs):
127
+ raise ValueError('resource_type_context_missing')
128
+ scores = self.model(context.half().float().cpu())[0]
129
+ if self.raw_weight:
130
+ raw_rows = [character_features(row['text'], self.raw_ngrams, self.raw_buckets) for row in inputs]
131
+ scores = scores.lerp(self.raw_model(pack_features(raw_rows)), self.raw_weight)
132
+ else:
133
+ rows = [character_features(row['text'], self.ngrams, self.buckets) for row in inputs]
134
+ scores = self.model(pack_features(rows))
135
+ typed = {}
136
+ scaled = scores / self.temperature
137
+ probabilities = scaled.softmax(-1).tolist()
138
+ for row, kind, values in zip(inputs, output_type(scaled, self.labels), probabilities, strict=True):
139
+ totals = {}
140
+ for label, score in zip(self.labels, values, strict=True):
141
+ mapped = self.biblatex_type_map[label]
142
+ totals[mapped] = totals.get(mapped, 0.) + score
143
+ ranked = sorted(totals.items(), key=lambda pair: (-pair[1], pair[0]))
144
+ top_label, top_score = ranked[0]
145
+ kind['biblatex'] = {
146
+ 'selected': top_label if top_score >= .90 else None,
147
+ 'candidates': [{'type': label, 'score': score} for label, score in ranked],
148
+ }
149
+ if kind['confidence'] < self.threshold:
150
+ kind['label'] = None
151
+ typed[row['id']] = kind
152
+ if typed.keys() != {row['id'] for row in predictions}:
153
+ raise ValueError('resource_type_predictions_misaligned')
154
+ return [{**row, 'resource_type': typed[row['id']]} for row in predictions]
155
+
156
+
157
+ class TypeFieldCountEvidence(nn.Module):
158
+ def __init__(self, classifier: ResourceTypeOutput, fields: int) -> None:
159
+ super().__init__()
160
+ self.classifier = classifier
161
+ self.fields = fields
162
+
163
+ def forward(self, hidden: Tensor, outer: Tensor, lengths: Tensor) -> Tensor:
164
+ bias = self.classifier.field_evidence(pool_context(hidden, lengths, outer), self.fields)
165
+ zero_counts = torch.zeros_like(bias).unsqueeze(-1)
166
+ return torch.cat((zero_counts, bias.unsqueeze(-1).expand(-1, -1, 3)), dim=-1)
pytorch/resource_type_raw.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "labels": [
3
+ "authored_book",
4
+ "book_chapter",
5
+ "conference_paper",
6
+ "dataset",
7
+ "edited_book",
8
+ "journal_article",
9
+ "proceedings",
10
+ "report",
11
+ "software",
12
+ "thesis",
13
+ "translated_book",
14
+ "web"
15
+ ],
16
+ "ngrams": [
17
+ 2,
18
+ 3,
19
+ 4,
20
+ 5
21
+ ],
22
+ "buckets": 32768,
23
+ "width": 12,
24
+ "work_weight": 0.0,
25
+ "class_weight": 0.0,
26
+ "learning_rate": 0.12
27
+ }
pytorch/resource_type_raw.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b49fd0accea70d1138473da425a326311d9cd9574fceb97da21df42f62f43e5
3
+ size 786968
pytorch/shared/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """分析スクリプトで共有するモジュール。"""
pytorch/shared/bibform_trial.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """bibformDatasetTrialの役割付き文字範囲と、原文だけを使う評価契約。"""
2
+ from collections import Counter, defaultdict
3
+ from copy import deepcopy
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import random
8
+
9
+ from shared.csl_spans import canonical_annotations
10
+ from shared.dataset_schema import FIELD_MAP, visible_value
11
+ from shared.text_offsets import transform_characters
12
+
13
+
14
+ NAME = 'bibformDatasetTrial'
15
+ FIELDS = ('TITLE', 'CONTAINER_TITLE', 'DATE', 'VOLUME', 'ISSUE', 'PAGES', 'ISSUER',
16
+ 'DOI', 'ISBN', 'URL', 'EDITION', 'VERSION')
17
+ ROLES = ('author.work', 'editor.work', 'translator.work', 'author.container',
18
+ 'editor.container', 'translator.container')
19
+
20
+
21
+ def validate(text: str, target: dict) -> None:
22
+ if set(target) != {'id', 'fields', 'contributors'}:
23
+ raise ValueError('invalid_trial_target_keys')
24
+ previous = 0
25
+ for field in target['fields']:
26
+ if field['label'] not in FIELDS or not previous <= field['start'] < field['end'] <= len(text):
27
+ raise ValueError('invalid_trial_field')
28
+ previous = field['end']
29
+ if field['value'] != visible_value(text[field['start']:field['end']], field['label']):
30
+ raise ValueError('trial_field_not_grounded')
31
+ previous = 0
32
+ for person in target['contributors']:
33
+ if set(person) != {'kind', 'start', 'end', 'value', 'name_parts', 'roles'}:
34
+ raise ValueError('invalid_trial_contributor_keys')
35
+ a, b = person['start'], person['end']
36
+ if person['kind'] not in ('person', 'organization') or not previous <= a < b <= len(text):
37
+ raise ValueError('invalid_trial_contributor')
38
+ previous = b
39
+ if person['value'] != visible_value(text[a:b], 'CONTRIBUTOR'):
40
+ raise ValueError('trial_contributor_not_grounded')
41
+ if not person['roles'] or person['roles'] != sorted(set(person['roles'])) or set(person['roles']) - set(ROLES):
42
+ raise ValueError('invalid_trial_roles')
43
+ parts = []
44
+ for part, span in person['name_parts'].items():
45
+ if part not in ('family', 'given') or not a <= span['start'] < span['end'] <= b:
46
+ raise ValueError('invalid_trial_name_part')
47
+ if span['value'] != visible_value(text[span['start']:span['end']], part):
48
+ raise ValueError('trial_name_not_grounded')
49
+ parts.append((span['start'], span['end']))
50
+ if len(parts) == 2 and max(parts[0][0], parts[1][0]) < min(parts[0][1], parts[1][1]):
51
+ raise ValueError('trial_name_parts_overlap')
52
+ if person['kind'] == 'organization' and parts:
53
+ raise ValueError('organization_with_person_parts')
54
+ if any(f['start'] < b and f['end'] > a for f in target['fields']):
55
+ raise ValueError('trial_contributor_field_overlap')
56
+
57
+
58
+ def from_rendered(identifier: str, html: str, plain_html: str) -> tuple[str, dict, list[dict]]:
59
+ text, annotations = canonical_annotations(html, plain_html)
60
+ fields, contributors, trace = [], [], []
61
+ for label, start, end in annotations:
62
+ if label.startswith(('TRIAL_PERSON:', 'TRIAL_ORGANIZATION:')):
63
+ kind, source, roles = label.removeprefix('TRIAL_').split(':')
64
+ person = {'kind': kind.lower(), 'start': start, 'end': end,
65
+ 'value': visible_value(text[start:end], 'CONTRIBUTOR'), 'name_parts': {},
66
+ 'roles': sorted(roles.split('+'))}
67
+ for part, left, right in annotations:
68
+ if part in ('FAMILY', 'GIVEN') and start <= left < right <= end:
69
+ if part.lower() in person['name_parts']:
70
+ raise ValueError('fragmented_trial_name')
71
+ person['name_parts'][part.lower()] = {'start': left, 'end': right,
72
+ 'value': visible_value(text[left:right], part)}
73
+ contributors.append(person)
74
+ trace.append({'source_person_index': int(source), 'start': start, 'end': end,
75
+ 'roles': person['roles']})
76
+ elif label in FIELD_MAP and FIELD_MAP[label] in FIELDS:
77
+ fields.append({'label': FIELD_MAP[label], 'start': start, 'end': end,
78
+ 'value': visible_value(text[start:end], FIELD_MAP[label])})
79
+ fields.sort(key=lambda f: (f['start'], -f['end']))
80
+ unique = []
81
+ for field in fields:
82
+ if unique and field['start'] < unique[-1]['end']:
83
+ if field == unique[-1]:
84
+ continue
85
+ raise ValueError('overlapping_trial_fields')
86
+ unique.append(field)
87
+ contributors.sort(key=lambda p: (p['start'], p['end']))
88
+ target = {'id': identifier, 'fields': unique, 'contributors': contributors}
89
+ validate(text, target)
90
+ if not any(f['label'] == 'TITLE' for f in unique) or not contributors:
91
+ raise ValueError('trial_missing_title_or_responsibility')
92
+ return text, target, trace
93
+
94
+
95
+ def signature(row: dict, *, include_roles: bool = True) -> tuple:
96
+ fields = tuple(sorted((f['label'], f['start'], f['end']) for f in row['fields']))
97
+ people = tuple(sorted((p['kind'], p['start'], p['end'],
98
+ tuple(sorted((k, s['start'], s['end']) for k, s in p['name_parts'].items())),
99
+ tuple(p.get('roles', [])) if include_roles else ()) for p in row['contributors']))
100
+ return fields, people
101
+
102
+
103
+ def formatting_noise(text: str, target: dict, seed: int, identifier: str) -> tuple[str, dict]:
104
+ rng = random.Random(seed)
105
+ punctuation = {',': ',', ';': ';', ':': ':', '(': '(', ')': ')', '[': '[', ']': ']'}
106
+ replacements = []
107
+ for char in text:
108
+ if char == ' ' and rng.random() < .12:
109
+ replacements.append('\n' if rng.random() < .5 else ' ')
110
+ elif char in punctuation and rng.random() < .4:
111
+ replacements.append(punctuation[char])
112
+ elif char in ('–', '—') and rng.random() < .5:
113
+ replacements.append('-')
114
+ else:
115
+ replacements.append(char)
116
+ result = deepcopy(target); result['id'] = identifier
117
+ annotations, objects = [], []
118
+ for field in result['fields']:
119
+ annotations.append((str(len(objects)), field['start'], field['end'])); objects.append((field, field['label']))
120
+ for person in result['contributors']:
121
+ annotations.append((str(len(objects)), person['start'], person['end'])); objects.append((person, 'CONTRIBUTOR'))
122
+ for part, span in person['name_parts'].items():
123
+ annotations.append((str(len(objects)), span['start'], span['end'])); objects.append((span, part))
124
+ text, transformed = transform_characters(text, annotations, replacements)
125
+ if len(transformed) != len(objects):
126
+ raise ValueError('noise_removed_annotated_content')
127
+ for key, start, end in transformed:
128
+ obj, label = objects[int(key)]
129
+ obj.update(start=start, end=end, value=visible_value(text[start:end], label))
130
+ validate(text, result)
131
+ return text, result
132
+
133
+
134
+ def trim_whitespace_boundaries(text: str, prediction: dict) -> dict:
135
+ """範囲注釈の規約に合わせ、原文の空白を範囲の両端から除く。"""
136
+ result = deepcopy(prediction)
137
+
138
+ def trim(span: dict) -> bool:
139
+ while span['start'] < span['end'] and text[span['start']].isspace():
140
+ span['start'] += 1
141
+ while span['end'] > span['start'] and text[span['end']-1].isspace():
142
+ span['end'] -= 1
143
+ return span['start'] < span['end']
144
+
145
+ result['fields'] = [field for field in result['fields'] if trim(field)]
146
+ people = []
147
+ for person in result['contributors']:
148
+ if trim(person):
149
+ person['name_parts'] = {key: span for key, span in person['name_parts'].items() if trim(span)}
150
+ people.append(person)
151
+ result['contributors'] = people
152
+ validate(text, result)
153
+ return result
154
+
155
+
156
+ BRACKET_GROUPS = (('((', '))'), ('[[', ']]'), ('{{', '}}'), ('「', '」'),
157
+ ('『', '』'), ('【', '】'), ('〔', '〕'), ('〈', '〉'), ('《', '》'))
158
+
159
+
160
+ def unmatched_terminal_closer(text: str, field: dict) -> str | None:
161
+ value=text[field['start']:field['end']]
162
+ if not value:return None
163
+ for opening,closing in BRACKET_GROUPS:
164
+ if value[-1] in closing and sum(value.count(c) for c in closing)>sum(value.count(c) for c in opening):
165
+ return closing[-1]
166
+ return None
167
+
168
+
169
+ def trim_unmatched_closing_boundaries(text: str, prediction: dict, allowed_pairs: list[list[str]]) -> dict:
170
+ """訓練正解で許された項目だけ、対応する開き括弧のない末尾を範囲から外す。"""
171
+ result=deepcopy(prediction);allowed={tuple(p) for p in allowed_pairs};fields=[]
172
+ for field in result['fields']:
173
+ while (closer:=unmatched_terminal_closer(text,field)) and (field['label'],closer) in allowed:
174
+ field['end']-=1
175
+ while field['end']>field['start'] and text[field['end']-1].isspace():field['end']-=1
176
+ if field['end']>field['start']:
177
+ field['value']=visible_value(text[field['start']:field['end']],field['label']);fields.append(field)
178
+ result['fields']=fields;validate(text,result);return result
179
+
180
+
181
+ def align_work_alias_roles(prediction: dict, blocked_transfers: list[list[str]] | None = None) -> dict:
182
+ """引用内の一意なフルネームに対応する姓の略記で、対象資料内の役割をそろえる。"""
183
+ result = deepcopy(prediction)
184
+ blocked = {tuple(pair) for pair in blocked_transfers or []}
185
+ full = defaultdict(set)
186
+ for person in result['contributors']:
187
+ parts = person['name_parts']
188
+ if person['kind'] == 'person' and set(parts) == {'family', 'given'}:
189
+ full[parts['family']['value']].add((parts['given']['value'], tuple(person['roles'])))
190
+ for person in result['contributors']:
191
+ parts, roles = person['name_parts'], person['roles']
192
+ if person['kind'] != 'person' or set(parts) != {'family'} or len(roles) != 1 or not roles[0].endswith('.work'):
193
+ continue
194
+ candidates = full.get(parts['family']['value'], set())
195
+ if len(candidates) == 1:
196
+ _, candidate_roles = next(iter(candidates))
197
+ if (len(candidate_roles) == 1 and candidate_roles[0].endswith('.work') and
198
+ (roles[0], candidate_roles[0]) not in blocked):
199
+ person['roles'] = list(candidate_roles)
200
+ return result
201
+
202
+
203
+ def evaluate(targets: list[dict], predictions: dict, metadata: dict) -> dict:
204
+ groups, conditions = defaultdict(list), defaultdict(list)
205
+ exact = structural = role_correct = role_total = 0
206
+ for target in targets:
207
+ prediction = predictions.get(target['id'], {'id': target['id'], 'fields': [], 'contributors': []})
208
+ hit = signature(target) == signature(prediction)
209
+ exact += hit
210
+ structural += signature(target, include_roles=False) == signature(prediction, include_roles=False)
211
+ row = metadata[target['id']]
212
+ groups[row['group_id']].append(int(hit)); conditions[row['condition']].append(int(hit))
213
+ predicted = {(p['kind'], p['start'], p['end']): p for p in prediction['contributors']}
214
+ for p in target['contributors']:
215
+ role_total += 1
216
+ other = predicted.get((p['kind'], p['start'], p['end']))
217
+ role_correct += bool(other and other.get('roles') == p['roles'])
218
+ count = len(targets)
219
+ return {'records': count, 'reference_exact': exact, 'reference_exact_rate': exact / max(count, 1),
220
+ 'primary_group_macro_exact': sum(sum(v)/len(v) for v in groups.values())/max(len(groups), 1),
221
+ 'work_groups': len(groups), 'without_roles_reference_exact_rate': structural/max(count, 1),
222
+ 'contributor_with_roles_correct': role_correct, 'gold_contributors': role_total,
223
+ 'contributor_with_roles_recall': role_correct/max(role_total, 1),
224
+ 'by_condition': {k: {'records': len(v), 'exact': sum(v), 'accuracy': sum(v)/len(v)}
225
+ for k, v in sorted(conditions.items())}}
pytorch/shared/bibform_trial_adapters.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """既存の重みを保存したまま、選んだ線形層へ小さな学習可能な差分を加える。"""
2
+ from pathlib import Path
3
+
4
+ from safetensors.torch import load_file
5
+ import torch
6
+ from torch import nn
7
+
8
+
9
+ class AdapterLinear(nn.Module):
10
+ def __init__(self, base: nn.Linear, rank: int, alpha: float) -> None:
11
+ super().__init__()
12
+ self.base = base
13
+ self.in_features, self.out_features = base.in_features, base.out_features
14
+ self.down = nn.Linear(base.in_features, rank, bias=False)
15
+ self.up = nn.Linear(rank, base.out_features, bias=False)
16
+ self.scale = alpha/rank
17
+ nn.init.zeros_(self.up.weight)
18
+ self.to(device=base.weight.device, dtype=base.weight.dtype)
19
+
20
+ @property
21
+ def weight(self):
22
+ return self.base.weight
23
+
24
+ @property
25
+ def bias(self):
26
+ return self.base.bias
27
+
28
+ def forward(self, features):
29
+ return self.base(features)+self.up(self.down(features))*self.scale
30
+
31
+
32
+ def install_adapters(member: nn.Module, configuration: dict) -> dict:
33
+ member.requires_grad_(False)
34
+ config = dict(configuration)
35
+ layers = member.encoder.encoder.layer
36
+ if 'targets' not in config:
37
+ selected = list(range(len(layers)-config['last_layers'], len(layers)))
38
+ if not selected or min(selected) < 0:
39
+ raise ValueError('invalid_adapter_layer_count')
40
+ suffixes = ('attention.self.query', 'attention.self.key', 'attention.self.value',
41
+ 'attention.output.dense', 'intermediate.dense', 'output.dense')
42
+ config['targets'] = [f'encoder.encoder.layer.{index}.{suffix}' for index in selected for suffix in suffixes]
43
+ config['targets'].append('projection')
44
+ if member.global_projection is not None:
45
+ config['targets'].append('global_projection')
46
+ config['normalizations'] = [f'encoder.encoder.layer.{index}.{name}' for index in selected
47
+ for name, module in layers[index].named_modules() if isinstance(module, nn.LayerNorm)]
48
+ for name in config['targets']:
49
+ base = member.get_submodule(name)
50
+ if not isinstance(base, nn.Linear):
51
+ raise ValueError(f'adapter_target_not_linear:{name}')
52
+ parent, _, key = name.rpartition('.')
53
+ rank = config.get('target_ranks', {}).get(name, config['rank'])
54
+ alpha = config.get('target_alphas', {}).get(name, config['alpha'])
55
+ if rank < 1 or alpha <= 0:
56
+ raise ValueError('invalid_adapter_rank_or_scale')
57
+ wrapper = AdapterLinear(base, rank, alpha)
58
+ setattr(member.get_submodule(parent) if parent else member, key, wrapper)
59
+ if base.bias is not None and config.get('train_biases', True):
60
+ base.bias.requires_grad_(True)
61
+ for name in config['normalizations']:
62
+ module = member.get_submodule(name)
63
+ if not isinstance(module, nn.LayerNorm):
64
+ raise ValueError('adapter_normalization_mismatch')
65
+ if config.get('train_normalizations', True):
66
+ module.requires_grad_(True)
67
+ names = sorted(name for name, parameter in member.named_parameters() if parameter.requires_grad)
68
+ if 'trainable_parameters' in config:
69
+ assert names == config['trainable_parameters']
70
+ config['trainable_parameters'] = names
71
+ config['trainable_parameter_count'] = sum(parameter.numel() for parameter in member.parameters() if parameter.requires_grad)
72
+ return config
73
+
74
+
75
+ def trainable_state(member: nn.Module, configuration: dict, half: bool = False) -> dict:
76
+ parameters = dict(member.named_parameters())
77
+ return {name: (parameters[name].detach().cpu().half() if half else parameters[name].detach().cpu()).contiguous()
78
+ for name in configuration['trainable_parameters']}
79
+
80
+
81
+ def load_adapter_state(member: nn.Module, configuration: dict, source: Path | dict) -> None:
82
+ state = load_file(source) if isinstance(source, Path) else source
83
+ assert set(state) == set(configuration['trainable_parameters'])
84
+ missing, unexpected = member.load_state_dict(state, strict=False)
85
+ assert not unexpected and not set(missing) & set(configuration['trainable_parameters'])
pytorch/shared/bibform_trial_model.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """原文の固定文字表現から、書誌範囲・姓名・人物ごとの複数役割を予測する。"""
2
+ from pathlib import Path
3
+ import json
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+ from safetensors.torch import load_file
10
+
11
+ from shared.bibform_trial import FIELDS, ROLES, validate
12
+ from shared.dataset_schema import bio_labels
13
+ from shared.span_tagger import EncodedCitation, OUTER_NAMES, NAME_NAMES, load_package
14
+ from shared.inference_strategies import structural_predictions
15
+ from shared.range_extraction import RANGE_TYPES, prediction_from_ranges
16
+ from shared.range_extraction import position_features
17
+
18
+
19
+ def utf8_character_ids(text: str) -> np.ndarray:
20
+ values = np.frombuffer(text.encode('utf-8'), dtype=np.uint8)
21
+ first = (values & 0xc0) != 0x80
22
+ offsets = np.arange(len(values))
23
+ starts = np.maximum.accumulate(np.where(first, offsets, 0))
24
+ result = np.zeros((len(text), 4), dtype=np.int64)
25
+ result[first.cumsum()-1, offsets-starts] = values.astype(np.int64)+1
26
+ return result
27
+
28
+
29
+ class RawCharacterEncoder(nn.Module):
30
+ def __init__(self, output_width: int = 192, dilations: tuple[int, ...] = (1,1)) -> None:
31
+ super().__init__()
32
+ self.bytes = nn.Embedding(257, 16, padding_idx=0)
33
+ self.convolutions = nn.ModuleList(nn.Conv1d(64,64,5,padding=2*d,dilation=d) for d in dilations)
34
+ self.norms = nn.ModuleList(nn.LayerNorm(64) for _ in self.convolutions)
35
+ self.projection = nn.Linear(64, output_width)
36
+ nn.init.zeros_(self.projection.weight); nn.init.zeros_(self.projection.bias)
37
+
38
+ def forward(self, values, lengths):
39
+ hidden = self.bytes(values).flatten(-2)
40
+ mask = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None]
41
+ for convolution, norm in zip(self.convolutions, self.norms):
42
+ hidden = norm(hidden+F.gelu(convolution(hidden.transpose(1, 2)).transpose(1, 2)))*mask
43
+ return self.projection(hidden)
44
+
45
+
46
+ class CitationAttention(nn.Module):
47
+ def __init__(self, width: int = 192) -> None:
48
+ super().__init__()
49
+ self.norm_attention = nn.LayerNorm(width)
50
+ self.attention = nn.MultiheadAttention(width, 6, dropout=.1, batch_first=True)
51
+ self.norm_output = nn.LayerNorm(width)
52
+ self.feedforward = nn.Sequential(nn.Linear(width, 2*width), nn.GELU(), nn.Dropout(.1), nn.Linear(2*width, width))
53
+ nn.init.zeros_(self.attention.out_proj.weight); nn.init.zeros_(self.attention.out_proj.bias)
54
+ nn.init.zeros_(self.feedforward[-1].weight); nn.init.zeros_(self.feedforward[-1].bias)
55
+
56
+ def forward(self, hidden, positions, mask):
57
+ values = self.norm_attention(hidden)+.1*positions
58
+ context = self.attention(values, values, values, key_padding_mask=mask, need_weights=False)[0]
59
+ hidden = hidden+F.dropout(context, .1, self.training)
60
+ return hidden+F.dropout(self.feedforward(self.norm_output(hidden)), .1, self.training)
61
+
62
+
63
+ class RoleGlobalContext(nn.Module):
64
+ def __init__(self, width: int = 192) -> None:
65
+ super().__init__()
66
+ self.query = nn.Sequential(nn.LayerNorm(5*width), nn.Linear(5*width, width))
67
+ self.keys = nn.LayerNorm(width)
68
+ self.position = nn.Linear(1, width)
69
+ self.attention = nn.MultiheadAttention(width, 6, dropout=.1, batch_first=True)
70
+ self.output = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, 5*width))
71
+ nn.init.zeros_(self.output[-1].weight)
72
+ nn.init.zeros_(self.output[-1].bias)
73
+
74
+ def forward(self, hidden, lengths, batch, values):
75
+ positions = torch.arange(hidden.shape[1], device=hidden.device, dtype=hidden.dtype)
76
+ positions = positions[None, :, None]/lengths[:, None, None].clamp_min(1)
77
+ keys = self.keys(hidden)+self.position(positions)
78
+ mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None]
79
+ context = self.attention(self.query(values)[:, None], keys[batch], keys[batch],
80
+ key_padding_mask=mask[batch], need_weights=False)[0][:, 0]
81
+ return self.output(context)
82
+
83
+
84
+ class RoleSummaryContext(nn.Module):
85
+ def __init__(self, width: int = 192) -> None:
86
+ super().__init__()
87
+ self.network = nn.Sequential(nn.LayerNorm(7*width+6), nn.Linear(7*width+6, 64), nn.GELU(),
88
+ nn.Dropout(.1), nn.Linear(64, 5*width))
89
+ nn.init.zeros_(self.network[-1].weight); nn.init.zeros_(self.network[-1].bias)
90
+
91
+ def forward(self, hidden, lengths, batch, start, end, values):
92
+ valid = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None]
93
+ mean = (hidden*valid).sum(1)/lengths[:, None]
94
+ maximum = hidden.masked_fill(~valid, -torch.inf).amax(1)
95
+ counts = torch.bincount(batch, minlength=len(lengths))
96
+ offsets = counts.cumsum(0)-counts
97
+ rank = torch.arange(len(batch), device=hidden.device)-torch.repeat_interleave(offsets, counts)
98
+ size = lengths[batch].float(); number = counts[batch].float()
99
+ positions = torch.stack([start/size, end/size, (end-start)/size,
100
+ rank/(number-1).clamp_min(1), number/(number+1), 1/size], -1)
101
+ features = torch.cat([values, mean[batch], maximum[batch], positions], -1)
102
+ return self.network(features)
103
+
104
+
105
+ def structural_loss_mean(losses, weights, mode, hard_fraction=.25):
106
+ weighted = losses*weights
107
+ if mode == 'token_mean':
108
+ return weighted.sum()/weights.sum().clamp_min(1)
109
+ if mode == 'reference_mean' or hard_fraction == 1:
110
+ return (weighted.sum(1)/weights.sum(1).clamp_min(1)).mean()
111
+ if mode != 'reference_hard' or not 0 < hard_fraction <= 1:
112
+ raise ValueError('invalid_structural_loss')
113
+ order = weighted.masked_fill(weights <= 0, -torch.inf).argsort(1, descending=True)
114
+ counts = ((weights > 0).sum(1)*hard_fraction).ceil().long()
115
+ selected = torch.arange(losses.shape[1], device=losses.device)[None, :] < counts[:, None]
116
+ numerator = (weighted.gather(1, order)*selected).sum(1)
117
+ denominator = (weights.gather(1, order)*selected).sum(1).clamp_min(1)
118
+ return (numerator/denominator).mean()
119
+
120
+
121
+ class TrialBIO(nn.Module):
122
+ def __init__(self, width: int = 768, role_weight: float = 1.0, context: int = 32,
123
+ sequence: str = 'none', semantic_width: int = 0, boundary_weight: float = 1.,
124
+ role_decoder: str = 'independent', structure: str = 'single_title', raw_characters: bool = False,
125
+ label_transitions: bool = False, transition_scale: float = 0., raw_semantic_width: int = 0,
126
+ attention_layers: int = 0, role_global_context: bool = False,
127
+ structural_loss: str = 'token_mean', hard_token_fraction: float = .25,
128
+ global_presence: bool = False, global_presence_weight: float = .1,
129
+ hidden_width: int = 192, role_hidden_width: int = 128,
130
+ role_summary_context: bool = False, raw_context_residual: bool = False,
131
+ additional_attention_layers: int = 0, additional_attention_scale: float = 1.) -> None:
132
+ super().__init__()
133
+ if hidden_width < 6 or hidden_width % 6 or role_hidden_width < 1:
134
+ raise ValueError('invalid_head_width')
135
+ self.hidden_width = hidden_width; self.role_hidden_width = role_hidden_width
136
+ self.features = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, hidden_width), nn.GELU())
137
+ self.outer = nn.Linear(hidden_width, 31); self.names = nn.Linear(hidden_width, 5)
138
+ self.role_head = nn.Sequential(nn.LayerNorm(5*hidden_width), nn.Linear(5*hidden_width, role_hidden_width), nn.GELU(), nn.Dropout(.1), nn.Linear(role_hidden_width, len(ROLES)))
139
+ self.role_global_context = role_global_context
140
+ if role_global_context:
141
+ self.role_global = RoleGlobalContext(hidden_width)
142
+ self.role_summary_context = role_summary_context
143
+ if role_summary_context:
144
+ self.role_summary = RoleSummaryContext(hidden_width)
145
+ self.global_presence = global_presence
146
+ self.field_presence_prior = None
147
+ self.global_presence_weight = global_presence_weight
148
+ if global_presence:
149
+ self.global_presence_head = nn.Sequential(nn.LayerNorm(2*hidden_width), nn.Linear(2*hidden_width, 128), nn.GELU(),
150
+ nn.Linear(128, len(FIELDS)+len(ROLES)))
151
+ self.global_presence_projection = nn.Linear(len(FIELDS)+len(ROLES), hidden_width)
152
+ nn.init.zeros_(self.global_presence_projection.weight)
153
+ nn.init.zeros_(self.global_presence_projection.bias)
154
+ self.register_buffer('presence_positive_weights', torch.ones(len(FIELDS)+len(ROLES)))
155
+ self.role_weight = role_weight; self.context = context
156
+ if structural_loss not in ('token_mean', 'reference_mean', 'reference_hard', 'contributors_only',
157
+ 'joint_crf', 'joint_crf_boundary') or not 0 < hard_token_fraction <= 1:
158
+ raise ValueError('invalid_structural_loss')
159
+ if structural_loss.startswith('joint_crf') and (structure != 'unrestricted' or not label_transitions):
160
+ raise ValueError('joint_sequence_loss_requires_the_joint_transition_decoder')
161
+ self.structural_loss = structural_loss; self.hard_token_fraction = hard_token_fraction
162
+ self.register_buffer('role_positive_weights', torch.ones(len(ROLES)))
163
+ self.base_width = width; self.semantic_width = semantic_width
164
+ self.raw_semantic_width = raw_semantic_width
165
+ if raw_semantic_width:
166
+ self.raw_semantic_features = nn.Sequential(nn.LayerNorm(raw_semantic_width), nn.Linear(raw_semantic_width, hidden_width))
167
+ nn.init.zeros_(self.raw_semantic_features[-1].weight)
168
+ nn.init.zeros_(self.raw_semantic_features[-1].bias)
169
+ self.boundary_weight = boundary_weight
170
+ if structure not in ('single_title', 'unrestricted'):
171
+ raise ValueError('unsupported_structure')
172
+ self.structure = structure
173
+ self.label_transitions = label_transitions
174
+ self.transition_scale = transition_scale
175
+ if label_transitions:
176
+ if structure != 'unrestricted':
177
+ raise ValueError('learned_label_transitions_require_unrestricted_structure')
178
+ for layer, size in (('outer', 31), ('names', 5)):
179
+ self.register_buffer(f'{layer}_transitions', torch.zeros(size, size))
180
+ self.register_buffer(f'{layer}_start', torch.zeros(size))
181
+ self.register_buffer(f'{layer}_end', torch.zeros(size))
182
+ self.raw_characters = raw_characters
183
+ if raw_characters:
184
+ self.raw_encoder = RawCharacterEncoder(hidden_width)
185
+ self.raw_context = None
186
+ if raw_context_residual:
187
+ self.install_raw_context()
188
+ if role_decoder not in ('independent', 'powerset'):
189
+ raise ValueError('unsupported_role_decoder')
190
+ self.role_decoder = role_decoder
191
+ if role_decoder == 'powerset':
192
+ masks = ((torch.arange(1, 2**len(ROLES))[:, None] >> torch.arange(len(ROLES))[None, :]) & 1).float()
193
+ self.register_buffer('role_masks', masks, persistent=False)
194
+ self.register_buffer('role_class_weights', torch.ones(len(masks)))
195
+ self.role_combo_bias = nn.Parameter(torch.zeros(len(masks)))
196
+ if semantic_width:
197
+ self.semantic_features = nn.Sequential(nn.LayerNorm(semantic_width), nn.Linear(semantic_width, hidden_width))
198
+ nn.init.zeros_(self.semantic_features[-1].weight); nn.init.zeros_(self.semantic_features[-1].bias)
199
+ if sequence not in ('none', 'bilstm', 'transformer'):
200
+ raise ValueError('unsupported_sequence_context')
201
+ self.sequence_kind = sequence
202
+ if sequence == 'bilstm':
203
+ self.sequence = nn.LSTM(hidden_width, hidden_width//2, batch_first=True, bidirectional=True)
204
+ self.sequence_projection = nn.Linear(hidden_width, hidden_width)
205
+ nn.init.zeros_(self.sequence_projection.weight); nn.init.zeros_(self.sequence_projection.bias)
206
+ elif sequence == 'transformer':
207
+ self.sequence = nn.ModuleList([CitationAttention(hidden_width) for _ in range(3)])
208
+ self.global_attention = nn.ModuleList([CitationAttention(hidden_width) for _ in range(attention_layers)])
209
+ self.additional_attention = nn.ModuleList([CitationAttention(hidden_width)
210
+ for _ in range(additional_attention_layers)])
211
+ self.additional_attention_scale = additional_attention_scale
212
+
213
+ def warm_start(self, path: Path) -> None:
214
+ missing, unexpected = self.load_state_dict(load_file(path), strict=False)
215
+ assert not unexpected
216
+ assert all(k.startswith(('role_head.', 'role_global.', 'role_summary.', 'sequence.', 'sequence_projection.', 'semantic_features.', 'raw_encoder.'))
217
+ or k in ('role_positive_weights', 'role_class_weights', 'role_combo_bias') for k in missing)
218
+
219
+ def install_raw_context(self) -> None:
220
+ if not self.raw_characters:
221
+ raise ValueError('raw_context_requires_original_character_features')
222
+ self.raw_context = RawCharacterEncoder(self.hidden_width,(1,2,4,8,16))
223
+
224
+ def encode(self, features, lengths, inputs=None, return_presence=False):
225
+ hidden = self.features(features[..., :self.base_width])
226
+ if self.semantic_width:
227
+ hidden = hidden+self.semantic_features(features[..., self.base_width:self.base_width+self.semantic_width])
228
+ if self.raw_semantic_width:
229
+ hidden = hidden+self.raw_semantic_features(features[..., self.base_width+self.semantic_width:])
230
+ if self.raw_characters:
231
+ if inputs is None:
232
+ raise ValueError('raw_character_encoder_requires_original_text')
233
+ byte_ids = np.zeros((len(inputs), features.shape[1], 4), dtype=np.int64)
234
+ for i, row in enumerate(inputs):
235
+ byte_ids[i, :len(row['text'])] = utf8_character_ids(row['text'])
236
+ byte_ids = torch.from_numpy(byte_ids).to(features.device)
237
+ hidden = hidden+self.raw_encoder(byte_ids,lengths)
238
+ if self.raw_context is not None:
239
+ hidden = hidden+self.raw_context(byte_ids,lengths)
240
+ if self.sequence_kind == 'bilstm':
241
+ packed = nn.utils.rnn.pack_padded_sequence(hidden, lengths.cpu(), batch_first=True, enforce_sorted=False)
242
+ contextual, _ = self.sequence(packed)
243
+ contextual, _ = nn.utils.rnn.pad_packed_sequence(contextual, batch_first=True, total_length=hidden.shape[1])
244
+ hidden = hidden+self.sequence_projection(F.dropout(contextual, .1, self.training))
245
+ elif self.sequence_kind == 'transformer':
246
+ positions = position_features(hidden.shape[1], self.hidden_width, hidden.device)[None, :, :]
247
+ mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None]
248
+ for layer in self.sequence:
249
+ hidden = layer(hidden, positions, mask)
250
+ if self.global_attention or self.additional_attention:
251
+ positions = position_features(hidden.shape[1], self.hidden_width, hidden.device)[None, :, :]
252
+ mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None]
253
+ for layer in self.global_attention:
254
+ hidden = layer(hidden, positions, mask)
255
+ if self.additional_attention and self.additional_attention_scale:
256
+ updated = hidden
257
+ for layer in self.additional_attention:
258
+ updated = layer(updated, positions, mask)
259
+ hidden = hidden.lerp(updated, self.additional_attention_scale)
260
+ presence = None
261
+ if self.global_presence:
262
+ valid = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None]
263
+ mean = (hidden*valid).sum(1)/lengths[:, None]
264
+ maximum = hidden.masked_fill(~valid, -torch.inf).amax(1)
265
+ presence = self.global_presence_head(torch.cat([mean, maximum], -1))
266
+ hidden = hidden+self.global_presence_projection(presence.sigmoid())[:, None]
267
+ return (hidden, presence) if return_presence else hidden
268
+
269
+ def role_scores(self, hidden, lengths, mentions):
270
+ if not mentions:
271
+ return hidden.new_zeros((0, len(ROLES)))
272
+ device = hidden.device
273
+ batch = torch.tensor([m[0] for m in mentions], device=device)
274
+ start = torch.tensor([m[1] for m in mentions], device=device)
275
+ end = torch.tensor([m[2] for m in mentions], device=device)
276
+ prefix = F.pad(hidden.cumsum(1), (0, 0, 1, 0))
277
+ def mean(left, right):
278
+ return (prefix[batch, right]-prefix[batch, left])/(right-left).clamp_min(1)[:, None]
279
+ left = (start-self.context).clamp_min(0)
280
+ right = torch.minimum(end+self.context, lengths[batch])
281
+ values = torch.cat([hidden[batch, start], hidden[batch, end-1], mean(start, end),
282
+ mean(left, start), mean(end, right)], -1)
283
+ if self.role_global_context:
284
+ values = values+self.role_global(hidden, lengths, batch, values)
285
+ if self.role_summary_context:
286
+ values = values+self.role_summary(hidden, lengths, batch, start, end, values)
287
+ return self.role_head(values)
288
+
289
+ def loss(self, features, lengths, targets, inputs=None, consistency_groups=None, consistency_weight=0.,
290
+ return_supervision=False):
291
+ if self.global_presence:
292
+ hidden, presence = self.encode(features, lengths, inputs, return_presence=True)
293
+ presence_gold = np.zeros((len(targets), len(FIELDS)+len(ROLES)), dtype=np.float32)
294
+ else:
295
+ hidden = self.encode(features, lengths, inputs)
296
+ gold_values = np.full((len(targets), 2, features.shape[1]), -100, dtype=np.int64)
297
+ mentions, role_gold = [], []
298
+ for i, (target, length) in enumerate(zip(targets, lengths.tolist(), strict=True)):
299
+ if self.global_presence:
300
+ for field in target['fields']:
301
+ presence_gold[i, FIELDS.index(field['label'])] = 1
302
+ for person in target['contributors']:
303
+ for role in person['roles']:
304
+ presence_gold[i, len(FIELDS)+ROLES.index(role)] = 1
305
+ outer = [(f['label'], f['start'], f['end']) for f in target['fields']]
306
+ outer += [(p['kind'], p['start'], p['end']) for p in target['contributors']]
307
+ names = [(key, part['start'], part['end']) for p in target['contributors'] for key, part in p['name_parts'].items()]
308
+ gold_values[i, 0, :length] = bio_labels(length, outer, OUTER_NAMES)
309
+ gold_values[i, 1, :length] = bio_labels(length, names, NAME_NAMES)
310
+ for person in target['contributors']:
311
+ mentions.append((i, person['start'], person['end']))
312
+ role_gold.append([float(role in person['roles']) for role in ROLES])
313
+ gold = torch.from_numpy(gold_values).to(features.device)
314
+ structural = hidden.sum()*0
315
+ outer_logits, name_logits = self.outer(hidden), self.names(hidden)
316
+ joint = self.structural_loss.startswith('joint_crf')
317
+ if joint:
318
+ from shared.joint_sequence_loss import joint_sequence_loss
319
+ structural = joint_sequence_loss(outer_logits, name_logits, gold_values, lengths,
320
+ self.outer_transitions, self.names_transitions,
321
+ self.outer_start, self.names_start, self.outer_end, self.names_end,
322
+ self.transition_scale)
323
+ if not joint or self.structural_loss == 'joint_crf_boundary':
324
+ mode = 'token_mean' if joint else self.structural_loss
325
+ outer_tags = gold[:, 0]
326
+ if mode == 'contributors_only':
327
+ first = 1 + 2 * OUTER_NAMES.index('person')
328
+ non_contributors = outer_logits[..., :first].float().logsumexp(-1, keepdim=True)
329
+ outer_logits = torch.cat((non_contributors, outer_logits[..., first:]), dim=-1)
330
+ outer_tags = torch.where(outer_tags >= first, outer_tags - first + 1, outer_tags.clamp(max=0))
331
+ mode = 'reference_mean'
332
+ for logits, tags in ((outer_logits, outer_tags), (name_logits, gold[:, 1])):
333
+ losses = F.cross_entropy(logits.transpose(1, 2), tags, reduction='none')
334
+ valid = tags >= 0
335
+ classes = (tags+1)//2
336
+ next_classes = F.pad(classes[:, 1:], (0, 1), value=-1)
337
+ boundary = ((tags % 2 == 1) | (classes != next_classes)) & (tags > 0)
338
+ weights = valid.float()*(1+(self.boundary_weight-1)*boundary)
339
+ value = structural_loss_mean(losses, weights, mode, self.hard_token_fraction)
340
+ structural = structural+(.1*value if joint else value)
341
+ if mentions:
342
+ score = self.role_scores(hidden, lengths, mentions)
343
+ labels = torch.tensor(role_gold, device=features.device)
344
+ if self.role_decoder == 'powerset':
345
+ codes = (labels.long()*(1 << torch.arange(len(ROLES), device=features.device))).sum(-1)-1
346
+ roles = F.cross_entropy(score@self.role_masks.T+self.role_combo_bias, codes, weight=self.role_class_weights)
347
+ else:
348
+ roles = F.binary_cross_entropy_with_logits(score, labels, pos_weight=self.role_positive_weights)
349
+ else:
350
+ roles = hidden.sum()*0
351
+ labels = hidden.new_empty((0,len(ROLES)))
352
+ total = structural+self.role_weight*roles
353
+ if self.global_presence:
354
+ total = total+self.global_presence_weight*F.binary_cross_entropy_with_logits(
355
+ presence, torch.from_numpy(presence_gold).to(features.device), pos_weight=self.presence_positive_weights)
356
+ if not consistency_weight or consistency_groups is None:
357
+ return (total,gold,labels) if return_supervision else total
358
+ consistency = hidden.sum()*0
359
+ if consistency_groups is not None:
360
+ if len(consistency_groups) != len(targets):
361
+ raise ValueError('invalid_training_consistency_groups')
362
+ groups, views, spans, group_per_view = {}, {}, [], []
363
+ for batch, (target, group) in enumerate(zip(targets, consistency_groups, strict=True)):
364
+ annotated = [(('field', field['label']), field['start'], field['end']) for field in target['fields']]
365
+ annotated += [(('role', person['kind'], tuple(person['roles'])), person['start'], person['end'])
366
+ for person in target['contributors']]
367
+ for label, start, end in annotated:
368
+ key = (group, label)
369
+ group_id = groups.setdefault(key, len(groups))
370
+ if (group_id, batch) not in views:
371
+ views[group_id, batch] = len(views); group_per_view.append(group_id)
372
+ spans.append((batch, start, end, views[group_id, batch]))
373
+ counts = np.bincount(group_per_view) if spans else np.zeros(0, dtype=np.int64)
374
+ if np.any(counts > 1):
375
+ indices = torch.tensor(spans, device=hidden.device)
376
+ batch, start, end, view = indices.unbind(1)
377
+ prefix = F.pad(hidden.float().cumsum(1), (0, 0, 1, 0))
378
+ pooled = (prefix[batch, end]-prefix[batch, start])/(end-start)[:, None]
379
+ view_counts = torch.tensor(np.bincount([span[3] for span in spans]), device=hidden.device)
380
+ values = pooled.new_zeros(len(views), hidden.shape[-1]).index_add(0, view, pooled)/view_counts[:, None]
381
+ values = F.normalize(values, dim=-1)
382
+ ids = torch.tensor(group_per_view, device=hidden.device)
383
+ group_counts = torch.tensor(counts, device=hidden.device)
384
+ centres = values.new_zeros(len(groups), hidden.shape[-1]).index_add(0, ids, values)/group_counts[:, None]
385
+ centres = F.normalize(centres, dim=-1)
386
+ distances = (1-(values*centres[ids]).sum(-1)).clamp_min(0)
387
+ errors = distances.new_zeros(len(groups)).index_add(0, ids, distances)/group_counts
388
+ consistency = errors[group_counts > 1].mean()
389
+ total = total+consistency_weight*consistency
390
+ return (total,gold,labels) if return_supervision else total
391
+
392
+ @torch.inference_mode()
393
+ def decode_with_transitions(self, outer, names, lengths, inputs):
394
+ from shared.span_tagger import joint_constraint_tables, viterbi_paths, prediction_from_labels
395
+ states, legal, start, end = joint_constraint_tables()
396
+ outer_ids = torch.tensor([state[0] for state in states], device=outer.device)
397
+ name_ids = torch.tensor([state[1] for state in states], device=outer.device)
398
+ transitions = self.outer_transitions[outer_ids[:, None], outer_ids[None, :]]
399
+ transitions = transitions+self.names_transitions[name_ids[:, None], name_ids[None, :]]
400
+ initial = self.outer_start[outer_ids]+self.names_start[name_ids]
401
+ final = self.outer_end[outer_ids]+self.names_end[name_ids]
402
+ emissions = outer.float()[..., outer_ids]+names.float()[..., name_ids]
403
+ paths = viterbi_paths(emissions, [int(length) for length in lengths],
404
+ legal+self.transition_scale*transitions.cpu(),
405
+ start+self.transition_scale*initial.cpu(), end+self.transition_scale*final.cpu())
406
+ return [prediction_from_labels(row['id'], row['text'], [states[s][0] for s in path],
407
+ [states[s][1] for s in path])
408
+ for row, path in zip(inputs, paths, strict=True)]
409
+
410
+ @torch.inference_mode()
411
+ def predict(self, features, lengths, inputs, role_threshold: float = 0.0):
412
+ if self.field_presence_prior:
413
+ hidden, presence = self.encode(features, lengths, inputs, return_presence=True)
414
+ else:
415
+ hidden = self.encode(features, lengths, inputs)
416
+ outer, names = self.outer(hidden), self.names(hidden)
417
+ if self.field_presence_prior:
418
+ prior = self.field_presence_prior
419
+ odds = torch.tensor(prior['log_prior_odds'], device=outer.device, dtype=torch.float32)
420
+ eligible = torch.tensor(prior['eligible'], device=outer.device, dtype=torch.float32)
421
+ evidence = (presence[:, :len(FIELDS)]-self.presence_positive_weights[:len(FIELDS)].log()-odds).clamp(-10, 10)*eligible
422
+ starts = torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS], device=outer.device)
423
+ outer[:, :, starts] += prior['scale']*evidence[:, None, :]
424
+ results, mentions = self.decode_structures(outer, names, lengths, inputs)
425
+ return self.assign_roles(inputs, results, self.role_scores(hidden, lengths, mentions), role_threshold)
426
+
427
+ @torch.inference_mode()
428
+ def decode_structures(self, outer, names, lengths, inputs):
429
+ index = OUTER_NAMES.index('LOCATION')
430
+ outer[:, :, 1+2*index:3+2*index] = -10000
431
+ rows = [EncodedCitation(r['id'], r['text'], [0], [], [], [], None) for r in inputs]
432
+ intermediate = (self.decode_with_transitions(outer, names, lengths, inputs) if self.label_transitions else
433
+ structural_predictions([outer, names], rows, 1.,
434
+ {'structure': 'single_title'} if self.structure == 'single_title' else {}))
435
+ results, mentions = [], []
436
+ for i, (row, pred) in enumerate(zip(inputs, intermediate, strict=True)):
437
+ ranges = [(RANGE_TYPES.index(f['label']), f['start'], f['end'], 1.) for f in pred['fields'] if f['label'] in FIELDS]
438
+ for p in pred['contributors']:
439
+ ranges.append((RANGE_TYPES.index(p['kind']), p['start'], p['end'], 1.))
440
+ ranges += [(RANGE_TYPES.index(key), v['start'], v['end'], 1.) for key, v in p['name_parts'].items()]
441
+ result = (prediction_from_ranges(row['id'], row['text'], ranges)
442
+ if self.structure == 'single_title' else pred)
443
+ result['fields'] = [f for f in result['fields'] if f['label'] in FIELDS]
444
+ for person in result['contributors']:
445
+ mentions.append((i, person['start'], person['end']))
446
+ results.append(result)
447
+ return results, mentions
448
+
449
+ @torch.inference_mode()
450
+ def assign_roles(self, inputs, results, logits, role_threshold):
451
+ selected_roles = None
452
+ if self.role_decoder == 'powerset':
453
+ codes = (logits@self.role_masks.T+self.role_combo_bias).argmax(-1)
454
+ selected_roles = self.role_masks[codes].bool().cpu()
455
+ logits = logits.cpu()
456
+ offset = 0
457
+ for row, result in zip(inputs, results, strict=True):
458
+ for person in result['contributors']:
459
+ values = logits[offset]
460
+ active = selected_roles[offset] if selected_roles is not None else values > role_threshold
461
+ roles = [role for role, value in zip(ROLES, active, strict=True) if value]
462
+ offset += 1
463
+ person['roles'] = sorted(roles or [ROLES[int(values.argmax())]])
464
+ validate(row['text'], result)
465
+ return results
466
+
467
+
468
+ class TrialHeadEnsemble(nn.Module):
469
+ def __init__(self, heads: list[TrialBIO], weights: list[float]) -> None:
470
+ super().__init__()
471
+ if not heads or len(heads) != len(weights) or any(weight <= 0 for weight in weights):
472
+ raise ValueError('invalid_head_ensemble_weights')
473
+ if any(head.role_decoder != 'independent' for head in heads):
474
+ raise ValueError('head_ensemble_requires_independent_role_logits')
475
+ shapes = {(head.base_width, head.semantic_width, head.raw_semantic_width) for head in heads}
476
+ if len(shapes) != 1:
477
+ raise ValueError('head_ensemble_feature_widths_differ')
478
+ self.heads = nn.ModuleList(heads)
479
+ self.register_buffer('weights', torch.tensor(weights)/sum(weights))
480
+ self.role_head = nn.Identity()
481
+ self.role_decoder = 'independent'
482
+ self.raw_semantic_width = heads[0].raw_semantic_width
483
+
484
+ @torch.inference_mode()
485
+ def predict(self, features, lengths, inputs, role_threshold=0.):
486
+ hidden = [head.encode(features, lengths, inputs) for head in self.heads]
487
+ outer = [head.outer(value) for head, value in zip(self.heads, hidden, strict=True)]
488
+ names = [head.names(value) for head, value in zip(self.heads, hidden, strict=True)]
489
+ def merged(values):
490
+ return values[0] if len(values) == 1 else sum(weight*value for weight, value in zip(self.weights, values, strict=True))
491
+ results, mentions = self.heads[0].decode_structures(merged(outer), merged(names), lengths, inputs)
492
+ roles = [head.role_scores(value, lengths, mentions) for head, value in zip(self.heads, hidden, strict=True)]
493
+ logits = self.role_head(merged(roles))
494
+ return self.heads[0].assign_roles(inputs, results, logits, role_threshold)
495
+
496
+
497
+ class TrialPredictor:
498
+ def __init__(self, package: Path, device: str = 'cuda', *, track_encoder_gradients: bool = False) -> None:
499
+ self.device = device
500
+ if (package/'runtime_resources.json').exists():
501
+ from shared.package_resources import RuntimeResources
502
+ self.runtime_resources = RuntimeResources(package)
503
+ package = self.runtime_resources.path
504
+ self.base, _, _ = load_package(package, device)
505
+ if (package/'adapter_model.json').exists():
506
+ from shared.bibform_trial_adapters import install_adapters, load_adapter_state
507
+ adapter_settings = json.loads((package/'adapter_model.json').read_text())
508
+ install_adapters(self.base.members[0], adapter_settings)
509
+ load_adapter_state(self.base.members[0], adapter_settings, package/'adapter_weights.safetensors')
510
+ self.base.members[0].eval()
511
+ settings = json.loads((package/'trial_model.json').read_text())
512
+ self.input_members = settings.get('input_members', [0, 1, 2, 3])
513
+ assert self.input_members and self.input_members[0] == 0
514
+ assert sorted(set(self.input_members)) == self.input_members and self.input_members[-1] <= 3
515
+ assert len(self.base.members) == len(self.input_members)
516
+ def build_head() -> TrialBIO:
517
+ return TrialBIO(role_weight=settings['role_weight'], context=settings['context'],
518
+ sequence=settings.get('sequence', 'none'),
519
+ semantic_width=128 if settings.get('semantic_features') else 0,
520
+ role_decoder=settings.get('role_decoder', 'independent'),
521
+ structure=settings.get('structure', 'single_title'),
522
+ raw_characters=settings.get('raw_characters', False),
523
+ label_transitions=settings.get('label_transitions', False),
524
+ transition_scale=settings.get('transition_scale', 0.),
525
+ raw_semantic_width=settings.get('raw_semantic_width', 0),
526
+ attention_layers=settings.get('attention_layers', 0),
527
+ role_global_context=settings.get('role_global_context', False),
528
+ global_presence=settings.get('global_presence', False),
529
+ hidden_width=settings.get('hidden_width', 192),
530
+ role_hidden_width=settings.get('role_hidden_width', 128),
531
+ role_summary_context=settings.get('role_summary_context', False),
532
+ raw_context_residual=settings.get('raw_context_residual',False),
533
+ additional_attention_layers=settings.get('additional_attention_layers', 0),
534
+ additional_attention_scale=settings.get('additional_attention_scale', 1.)).to(device)
535
+ if settings.get('head_ensemble'):
536
+ heads = []
537
+ for member in settings['head_ensemble']:
538
+ head = build_head()
539
+ head.load_state_dict(load_file(package/member['file'], device=device)); heads.append(head)
540
+ self.head = TrialHeadEnsemble(heads, [member['weight'] for member in settings['head_ensemble']]).to(device)
541
+ else:
542
+ self.head = build_head()
543
+ self.head.load_state_dict(load_file(package/'trial_head.safetensors', device=device))
544
+ if settings.get('field_presence_prior'):
545
+ prior = settings['field_presence_prior']
546
+ assert not settings.get('head_ensemble') and self.head.global_presence
547
+ assert len(prior['log_prior_odds']) == len(prior['eligible']) == len(FIELDS)
548
+ assert np.isfinite(prior['log_prior_odds']).all() and 0 < prior['scale'] <= 1
549
+ assert all(isinstance(value, bool) for value in prior['eligible'])
550
+ self.head.field_presence_prior = prior
551
+ self.head.eval()
552
+ self.role_threshold = settings['role_threshold']; self.captured = {}; self.handles = []
553
+ self.trim_span_whitespace = settings.get('trim_span_whitespace', False)
554
+ self.align_work_alias_roles = settings.get('align_work_alias_roles', False)
555
+ self.work_alias_blocked_transfers = settings.get('work_alias_blocked_transfers', [])
556
+ self.unmatched_closer_policy = settings.get('unmatched_closer_policy', [])
557
+ self.count_guidance = None
558
+ self.field_span_refiner = None
559
+ self.name_context_refiner = None
560
+ if settings.get('count_guidance'):
561
+ from shared.global_field_counts import GlobalFieldCounts
562
+ from shared.count_guided_predictor import CountGuidedPredictor
563
+ assert not settings.get('head_ensemble')
564
+ policy = settings['count_guidance']
565
+ count_model = GlobalFieldCounts(policy.get('use_soft_mass',False)).to(device)
566
+ count_model.load_state_dict(load_file(package/policy['file'], device=device))
567
+ self.count_guidance = CountGuidedPredictor(count_model, policy['generation_scales'],
568
+ policy['ranking_scale'], policy['minimum_gain'])
569
+ if settings.get('compact_title_residual'):
570
+ from shared.compact_title_residual import CompactTitleResidual
571
+ assert self.count_guidance is not None
572
+ policy = settings['compact_title_residual']
573
+ correction = CompactTitleResidual(policy['width']).to(device)
574
+ correction.load_state_dict(load_file(package/policy['file'],device=device))
575
+ self.count_guidance.title_residual = correction.eval()
576
+ self.count_guidance.title_residual_scale = policy['scale']
577
+ if settings.get('compact_field_residual'):
578
+ from shared.compact_field_residual import CompactFieldResidual
579
+ assert self.count_guidance is not None
580
+ policy = settings['compact_field_residual']
581
+ correction = CompactFieldResidual(policy['width']).to(device)
582
+ correction.load_state_dict(load_file(package / policy['file'], device=device))
583
+ self.count_guidance.field_residual = correction.eval()
584
+ self.count_guidance.field_residual_scale = policy['scale']
585
+ if settings.get('field_span_refiner'):
586
+ from shared.field_span_classifier import FieldSpanClassifier,FieldSpanRefiner
587
+ policy=settings['field_span_refiner']
588
+ self.field_span_representation=policy.get('representation','auxiliary_characters')
589
+ assert self.field_span_representation in ('auxiliary_characters','main_hidden')
590
+ assert (self.input_members==[0,1,2,3] if self.field_span_representation=='auxiliary_characters'
591
+ else self.count_guidance is not None)
592
+ assert not policy['count_scale'] or self.count_guidance is not None
593
+ span_model=FieldSpanClassifier(policy['width'],policy.get('neural_context_width',0),
594
+ 192 if self.field_span_representation=='main_hidden' else 576)
595
+ span_model.load_state_dict(load_file(package/policy['file'],device='cpu'))
596
+ self.field_span_refiner=FieldSpanRefiner(span_model,policy['minimum_gain'],policy['count_scale'],policy['boundary_only'])
597
+ if settings.get('name_context_refiner'):
598
+ from shared.name_context_cnn import NameContextCNN,NameContextRefiner
599
+ assert self.count_guidance is not None
600
+ policy=settings['name_context_refiner'];name_model=NameContextCNN(policy['width'])
601
+ name_model.load_state_dict(load_file(package/policy['file'],device='cpu'))
602
+ self.name_context_refiner=NameContextRefiner(name_model,self.head,policy['residual_scale'],policy['minimum_gain'])
603
+ self.compact_path_ranker = None
604
+ if settings.get('compact_path_ranker'):
605
+ from shared.compact_path_ranker import CompactPathRanker
606
+ assert self.count_guidance is not None and self.field_span_refiner is None
607
+ policy = settings['compact_path_ranker']
608
+ ranker = CompactPathRanker(policy['width'])
609
+ ranker.load_state_dict(load_file(package/policy['file'],device='cpu'))
610
+ self.compact_path_ranker = ranker.eval()
611
+ self.path_ranker_policy = policy
612
+ self.count_guidance.capture_logits = True
613
+ self.compact_field_edits = None
614
+ if settings.get('compact_field_edits'):
615
+ from shared.compact_field_edits import CompactFieldEditRanker
616
+ assert self.count_guidance is not None and self.field_span_refiner is not None
617
+ assert self.field_span_representation == 'main_hidden'
618
+ assert self.field_span_refiner.model.neural_context_width == 0
619
+ policy = settings['compact_field_edits']
620
+ model = CompactFieldEditRanker(policy['width'])
621
+ model.load_state_dict(load_file(package/policy['file'],device='cpu'))
622
+ self.compact_field_edits = model.eval()
623
+ self.field_edit_threshold = policy['minimum_score']
624
+ self.field_edit_merges = policy.get('merges',False)
625
+ self.field_edit_contextual = policy.get('contextual',False)
626
+ self.field_edit_options = {'expanded_boundaries':True} if policy.get('expanded_boundaries') else {}
627
+ self.count_guidance.capture_logits = True
628
+ for i, member in enumerate(self.base.members):
629
+ def capture(module, args, index=i):
630
+ self.captured[index] = args[0] if track_encoder_gradients else args[0].detach()
631
+ self.handles.append(member.heads[0].register_forward_pre_hook(capture))
632
+ self.semantic_projection = None
633
+ self.character_proxy = None
634
+ self.character_feature_blend = settings.get('compact_character_feature_blend')
635
+ if settings.get('compact_character_proxy'):
636
+ from shared.compact_character_proxy import CompactCharacterProxy
637
+ expected_members = [0] if self.character_feature_blend is None else [0,3]
638
+ assert self.input_members == expected_members and settings.get('compact_semantic_bridge') and settings.get('semantic_features')
639
+ if self.character_feature_blend is not None and not 0. <= self.character_feature_blend <= 1.:
640
+ raise ValueError('invalid_character_feature_blend')
641
+ width = self.base.members[0].encoder.config.hidden_size
642
+ depth = settings.get('compact_character_proxy_contextual_depth', 0)
643
+ proxy = CompactCharacterProxy(width, contextual_depth=depth) if depth else CompactCharacterProxy(width)
644
+ self.character_proxy = proxy.to(device)
645
+ self.character_proxy.load_state_dict(load_file(package/settings['compact_character_proxy'], device=device))
646
+ self.character_proxy.eval()
647
+ if settings.get('semantic_features'):
648
+ self.semantic_projection = {key: value.to(device) for key, value in load_file(package/'semantic_projection.safetensors').items()}
649
+ semantic_width = len(self.semantic_projection['mean'])
650
+ bridge = None
651
+ if settings.get('compact_semantic_bridge'):
652
+ bridge = {key: value.float() for key, value in
653
+ load_file(package/settings['compact_semantic_bridge'], device=device).items()}
654
+ semantic_width = bridge['weight'].shape[1]
655
+ if bridge['weight'].shape[0] != len(self.semantic_projection['mean']):
656
+ raise ValueError('compact_semantic_bridge_output_width_mismatch')
657
+ def capture_semantics(module, args):
658
+ contextual = args[0][..., :semantic_width]
659
+ if not track_encoder_gradients:
660
+ contextual = contextual.detach()
661
+ if self.character_proxy is not None:
662
+ self.captured['proxy_context'] = contextual
663
+ if bridge is not None:
664
+ contextual = F.linear(contextual, bridge['weight'], bridge['bias'])
665
+ self.captured['semantic'] = contextual
666
+ self.handles.append(self.base.members[0].projection.register_forward_pre_hook(capture_semantics))
667
+
668
+ def _encode_characters(self, chunk):
669
+ rows = [EncodedCitation(r['id'], r['text'], [0], [], [], [], None) for r in chunk]
670
+ self.base.member_text_outputs(rows, self.device)
671
+ active = dict(zip(self.input_members, range(len(self.input_members)), strict=True))
672
+ lengths = torch.tensor([len(r['text']) for r in chunk], device=self.device)
673
+ components = [self.captured[active[i]] if i in active else
674
+ torch.zeros_like(self.captured[0]) for i in range(4)]
675
+ if self.character_proxy is not None:
676
+ context = self.captured['proxy_context']
677
+ mask = torch.arange(context.shape[1], device=self.device)[None,:] < lengths[:,None]
678
+ proxy = self.character_proxy(components[0].half().float(), context, mask)
679
+ components[3] = (proxy if self.character_feature_blend is None
680
+ else proxy.lerp(components[3].float(), self.character_feature_blend))
681
+ features = torch.cat(components, -1).half().float()
682
+ if self.semantic_projection is not None:
683
+ extra = ((self.captured['semantic'].float()-self.semantic_projection['mean'])@
684
+ self.semantic_projection['components'].T).half().float()
685
+ features = torch.cat([features, extra], -1)
686
+ if self.head.raw_semantic_width:
687
+ features = torch.cat([features, self.captured['semantic'].half().float()], -1)
688
+ return features, lengths
689
+
690
+ @torch.inference_mode()
691
+ def predict(self, inputs, batch_size: int = 16, *, feature_cache=None):
692
+ if batch_size < 1:
693
+ raise ValueError('batch_size_must_be_positive')
694
+ if any(set(r) != {'id', 'text'} or not isinstance(r['id'], str)
695
+ or not isinstance(r['text'], str) or not r['text'] for r in inputs):
696
+ raise ValueError('only_original_id_and_text_are_accepted')
697
+ if len({r['id'] for r in inputs}) != len(inputs):
698
+ raise ValueError('duplicate_input_id')
699
+ result = {}
700
+ ordered = sorted(inputs, key=lambda r: len(r['text']))
701
+ for begin in range(0, len(ordered), batch_size):
702
+ chunk = ordered[begin:begin+batch_size]
703
+ if feature_cache is None:
704
+ features, lengths = self._encode_characters(chunk)
705
+ else:
706
+ key = (self, self.character_feature_blend, tuple((row['id'], row['text']) for row in chunk))
707
+ if key not in feature_cache:
708
+ feature_cache[key] = self._encode_characters(chunk)
709
+ features, lengths = feature_cache[key]
710
+ texts = {row['id']: row['text'] for row in chunk}
711
+ predicted = (self.count_guidance.predict(self.head, features, lengths, chunk,
712
+ self.role_threshold, self._postprocess)
713
+ if self.count_guidance is not None else
714
+ self.head.predict(features, lengths, chunk, self.role_threshold))
715
+ if self.count_guidance is None:
716
+ predicted=[self._postprocess(texts[row['id']],row) for row in predicted]
717
+ if self.field_span_refiner is not None:
718
+ count_logp=self.count_guidance.last_count_logp if self.count_guidance is not None else None
719
+ neural_context=self.count_guidance.last_global_features if self.count_guidance is not None else None
720
+ span_features=(self.count_guidance.last_hidden if self.field_span_representation=='main_hidden' else features)
721
+ predicted=self.field_span_refiner.predict(span_features,chunk,predicted,count_logp,neural_context)
722
+ if self.name_context_refiner is not None:
723
+ predicted=self.name_context_refiner.predict(self.count_guidance.last_hidden,self.head,chunk,predicted)
724
+ if self.compact_path_ranker is not None:
725
+ from shared.compact_path_ranker import candidate_rows,comparisons
726
+ guide = self.count_guidance
727
+ alternatives = candidate_rows(self.head,guide.last_logits,guide.last_hidden,lengths,chunk,
728
+ self.role_threshold,self._postprocess,self.name_context_refiner,
729
+ self.path_ranker_policy['paths'])
730
+ vectors = comparisons(predicted,alternatives,guide.last_logits,guide.last_count_logp,lengths)
731
+ predicted = self.compact_path_ranker.predict(predicted,vectors,self.path_ranker_policy['minimum_score'])
732
+ if self.compact_field_edits is not None:
733
+ predicted = self.compact_field_edits.predict(chunk,predicted,self.count_guidance,
734
+ self.field_span_refiner.model,self.field_edit_threshold,
735
+ self.field_edit_merges,self.field_edit_contextual,**self.field_edit_options)
736
+ for row in predicted:
737
+ result[row['id']] = row
738
+ return [result[r['id']] for r in inputs]
739
+
740
+ def _postprocess(self, text, row):
741
+ if self.trim_span_whitespace:
742
+ from shared.bibform_trial import trim_whitespace_boundaries
743
+ row = trim_whitespace_boundaries(text, row)
744
+ if self.align_work_alias_roles:
745
+ from shared.bibform_trial import align_work_alias_roles
746
+ row = align_work_alias_roles(row, self.work_alias_blocked_transfers)
747
+ if self.unmatched_closer_policy:
748
+ from shared.bibform_trial import trim_unmatched_closing_boundaries
749
+ row = trim_unmatched_closing_boundaries(text, row, self.unmatched_closer_policy)
750
+ return row
pytorch/shared/compact_byte_extractor.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract citations from UTF-8 bytes aligned to the original character positions."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+
7
+ from shared.bibform_trial import trim_whitespace_boundaries
8
+ from shared.bibform_trial_model import TrialBIO,utf8_character_ids
9
+ from shared.range_extraction import position_features
10
+
11
+
12
+ WIDTH = 144
13
+ DEPTH = 8
14
+
15
+
16
+ def pack_bytes(rows,device):
17
+ lengths = [len(row['text']) for row in rows]
18
+ if not lengths or min(lengths)==0:
19
+ raise ValueError('byte_extractor_requires_nonempty_text')
20
+ values = np.zeros((len(rows),max(lengths),4),dtype=np.int64)
21
+ for index,row in enumerate(rows):
22
+ values[index,:lengths[index]] = utf8_character_ids(row['text'])
23
+ return torch.from_numpy(values).to(device),torch.tensor(lengths,device=device)
24
+
25
+
26
+ class CompactByteExtractor(nn.Module):
27
+ def __init__(self,width=WIDTH,depth=DEPTH):
28
+ super().__init__()
29
+ self.width = width
30
+ self.bytes = nn.Embedding(257,24,padding_idx=0)
31
+ self.project = nn.Linear(4*24,width)
32
+ self.local = nn.ModuleList(nn.Conv1d(width,width,3,padding=dilation,dilation=dilation)
33
+ for dilation in (1,2,4))
34
+ self.local_norm = nn.ModuleList(nn.LayerNorm(width) for _ in self.local)
35
+ self.layers = nn.ModuleList(nn.TransformerEncoderLayer(
36
+ width,6,dim_feedforward=2*width,dropout=.08,activation='gelu',batch_first=True,norm_first=True)
37
+ for _ in range(depth))
38
+ self.norm = nn.LayerNorm(width)
39
+ self.head = TrialBIO(width=width,hidden_width=width,role_hidden_width=96,
40
+ structure='unrestricted',label_transitions=True,
41
+ transition_scale=.25,role_decoder='powerset',boundary_weight=2.3,
42
+ structural_loss='reference_mean')
43
+
44
+ def encode(self,byte_ids,lengths):
45
+ width = byte_ids.size(1)
46
+ padding = torch.arange(width,device=byte_ids.device)[None,:]>=lengths[:,None]
47
+ valid = ~padding[...,None]
48
+ hidden = self.project(self.bytes(byte_ids).flatten(-2))*valid
49
+ for convolution,norm in zip(self.local,self.local_norm,strict=True):
50
+ local = torch.nn.functional.gelu(convolution(norm(hidden).transpose(1,2)).transpose(1,2))
51
+ hidden = (hidden+local)*valid
52
+ hidden = (hidden+.18*position_features(width,self.width,hidden.device)[None,...])*valid
53
+ for layer in self.layers:
54
+ hidden = layer(hidden,src_key_padding_mask=padding)*valid
55
+ return self.norm(hidden)*valid
56
+
57
+ @torch.inference_mode()
58
+ def predict(self,rows,device):
59
+ raw,lengths = pack_bytes(rows,device)
60
+ features = self.encode(raw,lengths)
61
+ return [trim_whitespace_boundaries(row['text'],result) for row,result in
62
+ zip(rows,self.head.predict(features,lengths,rows),strict=True)]
pytorch/shared/compact_character_proxy.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A small character branch using the compact encoder's existing context."""
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ class CompactCharacterProxy(nn.Module):
9
+ def __init__(self, context_width: int, character_width: int = 192, contextual_depth: int = 0) -> None:
10
+ super().__init__()
11
+ self.input = nn.Linear(context_width + character_width, character_width)
12
+ self.blocks = nn.ModuleList(nn.Conv1d(character_width, character_width, 3, padding=d, dilation=d)
13
+ for d in (1, 2, 4))
14
+ self.norms = nn.ModuleList(nn.LayerNorm(character_width) for _ in self.blocks)
15
+ self.output = nn.Linear(character_width, character_width)
16
+ nn.init.zeros_(self.output.weight)
17
+ nn.init.zeros_(self.output.bias)
18
+ self.context_blocks = nn.ModuleList(
19
+ nn.TransformerEncoderLayer(character_width, nhead=4, dim_feedforward=4*character_width,
20
+ dropout=.1, activation='gelu', batch_first=True, norm_first=True)
21
+ for _ in range(contextual_depth)
22
+ )
23
+ if self.context_blocks:
24
+ self.context_output = nn.Linear(character_width, character_width)
25
+ nn.init.zeros_(self.context_output.weight)
26
+ nn.init.zeros_(self.context_output.bias)
27
+
28
+ def forward(self, characters: Tensor, context: Tensor, valid: Tensor) -> Tensor:
29
+ mask = valid.unsqueeze(-1)
30
+ hidden = self.input(torch.cat((characters, context), -1)) * mask
31
+ for conv, norm in zip(self.blocks, self.norms, strict=True):
32
+ update = F.gelu(conv(hidden.transpose(1,2)).transpose(1,2))
33
+ hidden = norm(hidden + update) * mask
34
+ result = self.output(hidden)
35
+ if self.context_blocks:
36
+ full_context = hidden
37
+ for block in self.context_blocks:
38
+ full_context = block(full_context, src_key_padding_mask=~valid) * mask
39
+ result = result + self.context_output(full_context)
40
+ return result * mask
pytorch/shared/compact_edition_endpoint.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predict the end of a detected edition while keeping its original start."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+
7
+ from shared.bibform_trial_model import RawCharacterEncoder, utf8_character_ids
8
+ from shared.dataset_schema import visible_value
9
+
10
+
11
+ EDITION_RADIUS = 12
12
+
13
+
14
+ class CompactEditionEndpoint(nn.Module):
15
+ def __init__(self):
16
+ super().__init__()
17
+ self.encoded = nn.Linear(192,64)
18
+ self.bytes = RawCharacterEncoder(64,(1,2))
19
+ self.endpoint = nn.Sequential(nn.LayerNorm(193),nn.Linear(193,64),nn.GELU(),nn.Linear(64,1))
20
+
21
+ def forward(self,hidden,lengths,rows,starts):
22
+ values = np.zeros((*hidden.shape[:2],4),dtype=np.int64)
23
+ for i,row in enumerate(rows):
24
+ values[i,:len(row['text'])] = utf8_character_ids(row['text'])
25
+ state = self.encoded(hidden) + self.bytes(torch.from_numpy(values).to(hidden.device),lengths)
26
+ span_start = state[torch.arange(len(rows),device=hidden.device),starts]
27
+ edge = torch.zeros_like(state[:,:1])
28
+ left = torch.cat((edge,state),1)
29
+ right = torch.cat((state,edge),1)
30
+ positions = torch.arange(left.size(1),device=hidden.device)[None,:]
31
+ distance = ((positions-starts[:,None]).clamp(-32,64)/64.)[...,None]
32
+ return self.endpoint(torch.cat((left,right,span_start[:,None,:].expand_as(left),distance),-1)).squeeze(-1)
33
+
34
+
35
+ def edition(row):
36
+ matches = [field for field in row['fields'] if field['label']=='EDITION']
37
+ return matches[0] if len(matches)==1 else None
38
+
39
+
40
+ def end_positions(text,prediction,edition):
41
+ left,right = edition['start'],edition['end']
42
+ blockers = [*prediction['fields'],*prediction['contributors']]
43
+ stop = min((part['start'] for part in blockers if part['start']>=right),default=len(text))
44
+ begin = max(left+1,right-EDITION_RADIUS)
45
+ end = min(stop,right+EDITION_RADIUS)
46
+ return [offset for offset in range(begin,end+1) if not text[offset-1].isspace()]
47
+
48
+
49
+ def edition_edit(row,prediction,edition,scores):
50
+ old = edition['end']
51
+ positions = [offset for offset in end_positions(row['text'],prediction,edition) if offset!=old]
52
+ if not positions:
53
+ return None
54
+ chosen = max(positions,key=lambda offset:float(scores[offset]))
55
+ value = visible_value(row['text'][edition['start']:chosen],'EDITION')
56
+ adjusted = {**edition,'end':chosen,'value':value}
57
+ result = {**prediction,'fields':[adjusted if field is edition else field for field in prediction['fields']]}
58
+ return float(scores[chosen]-scores[old]),result
59
+
60
+
61
+ @torch.inference_mode()
62
+ def refine_edition_endpoints(rows,predictions,hidden,model,threshold):
63
+ editions = [(i,edition(prediction)) for i,prediction in enumerate(predictions)]
64
+ valid = [(i,field) for i,field in editions if field is not None]
65
+ if not valid:
66
+ return predictions
67
+ indices,fields = zip(*valid,strict=True)
68
+ raw = [rows[i] for i in indices]
69
+ lengths = torch.tensor([len(row['text']) for row in raw],device=hidden.device)
70
+ starts = torch.tensor([field['start'] for field in fields],device=hidden.device)
71
+ scores = model(hidden[list(indices)].float(),lengths,raw,starts).float().cpu().numpy()
72
+ updated = list(predictions)
73
+ for index,field,score in zip(indices,fields,scores,strict=True):
74
+ proposal = edition_edit(rows[index],predictions[index],field,score)
75
+ if proposal is not None and proposal[0]>threshold:
76
+ updated[index] = proposal[1]
77
+ return updated
pytorch/shared/compact_model_selector.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Choose between frozen extraction predictions using both models' character scores."""
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from shared.bibform_trial import ROLES, signature
7
+ from shared.compact_path_ranker import difference_vector
8
+
9
+
10
+ def enable_model_selection(models):
11
+ for model in models:
12
+ if model.count_guidance is None:
13
+ raise ValueError('model_selection_requires_character_scores')
14
+ model.count_guidance.capture_logits = True
15
+
16
+
17
+ def combine_fields_and_contributors(field_predictions, contributor_predictions):
18
+ combined = []
19
+ for fields, people in zip(field_predictions, contributor_predictions, strict=True):
20
+ if fields['id'] != people['id']:
21
+ raise ValueError('context_predictions_returned_different_ids')
22
+ contributors = people['contributors']
23
+ if any(field['start'] < person['end'] and person['start'] < field['end']
24
+ for field in fields['fields'] for person in contributors):
25
+ combined.append(fields)
26
+ else:
27
+ combined.append({**fields, 'contributors': contributors})
28
+ return combined
29
+
30
+
31
+ def role_confidence(model, rows, predictions, disagreements):
32
+ hidden = model.count_guidance.last_hidden
33
+ lengths = torch.tensor([len(row['text']) for row in rows], device=hidden.device)
34
+ mentions, assignments = [], []
35
+ for index in disagreements:
36
+ for person in predictions[index]['contributors']:
37
+ mentions.append((index, person['start'], person['end']))
38
+ assignments.append([role in person['roles'] for role in ROLES])
39
+ if not mentions:
40
+ return {index: np.zeros(len(ROLES) + 2, dtype=np.float32) for index in disagreements}
41
+ logits = model.head.role_scores(hidden, lengths, mentions).float() - model.role_threshold
42
+ signs = torch.tensor(assignments, device=logits.device, dtype=logits.dtype) * 2 - 1
43
+ scores = torch.nn.functional.logsigmoid(logits * signs).cpu().numpy()
44
+ result = {}
45
+ offset = 0
46
+ for index in disagreements:
47
+ count = len(predictions[index]['contributors'])
48
+ if count:
49
+ confidence = scores[offset:offset + count]
50
+ result[index] = np.concatenate((confidence.mean(0), [confidence.min(), confidence.max()]))
51
+ else:
52
+ result[index] = np.zeros(len(ROLES) + 2, dtype=np.float32)
53
+ offset += count
54
+ return result
55
+
56
+
57
+ @torch.inference_mode()
58
+ def model_comparisons(models, inputs, *, role_evidence=False, auxiliary_predictions=None, primary_feature_cache=None):
59
+ rows = sorted(inputs, key=lambda row:len(row['text']))
60
+ primary, auxiliary = models
61
+ base = (primary.predict(rows, len(rows)) if primary_feature_cache is None else
62
+ primary.predict(rows, len(rows), feature_cache=primary_feature_cache))
63
+ if auxiliary_predictions is None:
64
+ alternative = auxiliary.predict(rows, len(rows))
65
+ else:
66
+ alternative = auxiliary_predictions
67
+ if any(row['id'] != prediction['id'] for row, prediction in zip(rows, alternative, strict=True)):
68
+ raise ValueError('auxiliary_predictions_returned_different_ids')
69
+ disagreements = [i for i,(before,after) in enumerate(zip(base,alternative,strict=True))
70
+ if signature(before)!=signature(after)]
71
+ vectors = {}
72
+ if disagreements:
73
+ evidence = []
74
+ for model in models:
75
+ guide = model.count_guidance
76
+ evidence.append((tuple(t.float().log_softmax(-1).cpu().numpy() for t in guide.last_logits),
77
+ guide.last_count_logp))
78
+ role_differences = []
79
+ if role_evidence:
80
+ for model in models:
81
+ before = role_confidence(model, rows, base, disagreements)
82
+ after = role_confidence(model, rows, alternative, disagreements)
83
+ role_differences.append({i: after[i] - before[i] for i in disagreements})
84
+ for i in disagreements:
85
+ length = len(rows[i]['text'])
86
+ signals = [difference_vector(base[i],alternative[i],
87
+ tuple(logits[i,:length] for logits in scores), counts[i],0)
88
+ for scores,counts in evidence]
89
+ signals.extend(difference[i] for difference in role_differences)
90
+ vectors[i] = np.concatenate(signals)
91
+ return base, alternative, vectors
92
+
93
+
94
+ @torch.inference_mode()
95
+ def choose_predictions(models, inputs, selector, threshold, *, role_evidence=False,
96
+ auxiliary_predictions=None, primary_feature_cache=None):
97
+ base, alternative, vectors = model_comparisons(models, inputs, role_evidence=role_evidence,
98
+ auxiliary_predictions=auxiliary_predictions,
99
+ primary_feature_cache=primary_feature_cache)
100
+ if vectors:
101
+ scores = selector(torch.from_numpy(np.stack(list(vectors.values())))).tolist()
102
+ for index,score in zip(vectors,scores,strict=True):
103
+ if score > threshold:
104
+ base[index] = alternative[index]
105
+ return base
pytorch/shared/compact_path_ranker.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score plausible alternative character paths using their model evidence."""
2
+ from collections import Counter
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch import nn
7
+
8
+ from shared.bibform_trial import FIELDS, ROLES, signature
9
+ from shared.count_guided_candidates import count_vector
10
+ from shared.dataset_schema import bio_labels
11
+ from shared.kbest_viterbi import kbest_viterbi
12
+ from shared.span_tagger import (NAME_NAMES, OUTER_NAMES, joint_constraint_tables,
13
+ prediction_from_labels)
14
+
15
+
16
+ def _bio(row: dict, length: int) -> tuple[np.ndarray, np.ndarray]:
17
+ outer = [(f['label'], f['start'], f['end']) for f in row['fields']]
18
+ outer.extend((p['kind'],p['start'],p['end']) for p in row['contributors'])
19
+ names = [(key, span['start'],span['end']) for p in row['contributors'] for key,span in p['name_parts'].items()]
20
+ return np.asarray(bio_labels(length,outer,OUTER_NAMES)),np.asarray(bio_labels(length,names,NAME_NAMES))
21
+
22
+
23
+ def difference_vector(baseline: dict, candidate: dict, likelihoods: tuple[np.ndarray,np.ndarray],
24
+ count_logp: np.ndarray, rank: int) -> np.ndarray:
25
+ length = len(likelihoods[0])
26
+ before = _bio(baseline,length)
27
+ after = _bio(candidate,length)
28
+ old_counts,new_counts = count_vector(baseline),count_vector(candidate)
29
+ labels = np.arange(len(FIELDS))
30
+ values = [np.log1p(length),float(rank)]
31
+ values.extend((count_logp[labels,new_counts]-count_logp[labels,old_counts]) / 10.)
32
+ values.extend((new_counts-old_counts).tolist())
33
+ for old,new,score,category_count in zip(before,after,likelihoods,(len(OUTER_NAMES),len(NAME_NAMES)),strict=True):
34
+ changed = np.flatnonzero(old!=new)
35
+ if len(changed):
36
+ a,b = score[changed,old[changed]],score[changed,new[changed]]
37
+ delta = b-a
38
+ values.extend((len(changed)/10,changed[0]/length,changed[-1]/length,
39
+ delta.sum()/10,delta.mean(),delta.min(),delta.max(),a.mean(),b.mean()))
40
+ else:
41
+ values.extend([0.]*9)
42
+ old_class = (old+1)//2
43
+ new_class = (new+1)//2
44
+ for label in range(1,category_count+1):
45
+ leaving = (old_class==label) & (old!=new)
46
+ arriving = (new_class==label) & (old!=new)
47
+ values.extend((int(leaving.sum())/10,int(arriving.sum())/10))
48
+ roles_a = Counter(role for p in baseline['contributors'] for role in p['roles'])
49
+ roles_b = Counter(role for p in candidate['contributors'] for role in p['roles'])
50
+ values.extend(roles_b[r]-roles_a[r] for r in ROLES)
51
+ return np.asarray(values,dtype=np.float32)
52
+
53
+
54
+ @torch.inference_mode()
55
+ def candidate_rows(head, logits: tuple, hidden: torch.Tensor, lengths: torch.Tensor, rows: list[dict],
56
+ threshold: float, postprocess, name_refiner, k: int) -> list[list[tuple[int,dict]]]:
57
+ outer,names = logits
58
+ states, legal, initial, final = joint_constraint_tables()
59
+ outer_ids = torch.as_tensor([s[0] for s in states],device=outer.device)
60
+ name_ids = torch.as_tensor([s[1] for s in states],device=outer.device)
61
+ location = OUTER_NAMES.index('LOCATION')
62
+ work = outer.float().clone()
63
+ work[:,:,1+2*location:3+2*location] = -10000.
64
+ emissions = work[...,outer_ids] + names.float()[...,name_ids]
65
+ transitions = head.outer_transitions[outer_ids[:,None],outer_ids[None,:]]+head.names_transitions[name_ids[:,None],name_ids[None,:]]
66
+ start = head.outer_start[outer_ids]+head.names_start[name_ids]
67
+ end = head.outer_end[outer_ids]+head.names_end[name_ids]
68
+ allowed = legal+head.transition_scale*transitions.cpu()
69
+ paths = kbest_viterbi(emissions,lengths.tolist(),allowed,initial+head.transition_scale*start.cpu(),
70
+ final+head.transition_scale*end.cpu(),k)
71
+ result = [[] for _ in rows]
72
+ for rank in range(k):
73
+ indices, raw, subset = [], [], []
74
+ for i,(row,choices) in enumerate(zip(rows,paths,strict=True)):
75
+ if rank >= len(choices):
76
+ continue
77
+ choice = choices[rank]
78
+ pred = prediction_from_labels(row['id'],row['text'],[states[z][0] for z in choice],
79
+ [states[z][1] for z in choice])
80
+ pred['fields'] = [f for f in pred['fields'] if f['label'] in FIELDS]
81
+ indices.append(i); raw.append(pred); subset.append(row)
82
+ if not indices:
83
+ continue
84
+ mention = [(i,p['start'],p['end']) for i,pred in enumerate(raw) for p in pred['contributors']]
85
+ features, sizes = hidden[indices], lengths[indices]
86
+ assigned = head.assign_roles(subset,raw,head.role_scores(features,sizes,mention),threshold)
87
+ assigned = [postprocess(row['text'],pred) for row,pred in zip(subset,assigned,strict=True)]
88
+ if name_refiner:
89
+ assigned = name_refiner.predict(features,head,subset,assigned)
90
+ for i,pred in zip(indices,assigned,strict=True):
91
+ result[i].append((rank,pred))
92
+ return result
93
+
94
+
95
+ def comparisons(baseline: list[dict], candidates: list[list[tuple[int,dict]]], logits: tuple,
96
+ count_logp: np.ndarray, lengths: torch.Tensor) -> list[list[tuple[dict,np.ndarray]]]:
97
+ rows = []
98
+ log_probability = tuple(score.float().log_softmax(-1).cpu().numpy() for score in logits)
99
+ for i,(before,variants,length) in enumerate(zip(baseline,candidates,lengths.tolist(),strict=True)):
100
+ known = {signature(before)}
101
+ evidence = tuple(values[i,:length] for values in log_probability)
102
+ alternatives = []
103
+ for rank,after in variants:
104
+ difference = signature(after)
105
+ if difference in known:
106
+ continue
107
+ known.add(difference)
108
+ alternatives.append((after,difference_vector(before,after,evidence,count_logp[i],rank)))
109
+ rows.append(alternatives)
110
+ return rows
111
+
112
+
113
+ class CompactPathRanker(nn.Module):
114
+ def __init__(self, width: int) -> None:
115
+ super().__init__()
116
+ self.register_buffer('mean',torch.zeros(width))
117
+ self.register_buffer('scale',torch.ones(width))
118
+ self.regression = nn.Linear(width,1)
119
+
120
+ def forward(self, values: torch.Tensor) -> torch.Tensor:
121
+ return self.regression(((values-self.mean)/self.scale).clamp(-8.,8.)).squeeze(-1)
122
+
123
+ @torch.inference_mode()
124
+ def predict(self, baseline: list[dict], alternatives: list[list[tuple[dict,np.ndarray]]],
125
+ minimum_score: float) -> list[dict]:
126
+ flattened = [vector for variants in alternatives for _,vector in variants]
127
+ if not flattened:
128
+ return baseline
129
+ scores = self(torch.from_numpy(np.stack(flattened))).tolist()
130
+ selected=[]
131
+ offset=0
132
+ for old,variants in zip(baseline,alternatives,strict=True):
133
+ if variants:
134
+ best=max(range(len(variants)),key=lambda i:scores[offset+i])
135
+ selected.append(variants[best][0] if scores[offset+best]>minimum_score else old)
136
+ offset+=len(variants)
137
+ else:
138
+ selected.append(old)
139
+ return selected
pytorch/shared/compact_score_blend.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blend character-level extraction scores from two frozen models."""
2
+
3
+ import torch
4
+
5
+ from shared.global_field_counts import field_start_mass
6
+
7
+
8
+ def enable_score_blending(baseline, auxiliary):
9
+ for predictor in (baseline, auxiliary):
10
+ if (predictor.count_guidance is None or predictor.compact_path_ranker is not None
11
+ or predictor.compact_field_edits is not None):
12
+ raise ValueError('unsupported_score_blend_model')
13
+ predictor.count_guidance.capture_logits = True
14
+ if baseline.field_span_refiner is not None and baseline.field_span_representation != 'main_hidden':
15
+ raise ValueError('unsupported_score_blend_span_refiner')
16
+
17
+
18
+ @torch.inference_mode()
19
+ def decode_cached_scores(model, rows, outer, names):
20
+ guide = model.count_guidance
21
+ hidden = guide.last_hidden
22
+ lengths = torch.tensor([len(row['text']) for row in rows], device=hidden.device)
23
+ mass = field_start_mass(outer, lengths) if guide.model.use_soft_mass else None
24
+ result = guide.predict_from_scores(model.head, hidden, outer, names, lengths, rows,
25
+ model.role_threshold, model._postprocess, mass)
26
+ if model.field_span_refiner is not None:
27
+ if model.field_span_representation != 'main_hidden':
28
+ raise ValueError('unsupported_score_blend_span_refiner')
29
+ result = model.field_span_refiner.predict(hidden, rows, result, guide.last_count_logp,
30
+ guide.last_global_features)
31
+ if model.name_context_refiner is not None:
32
+ result = model.name_context_refiner.predict(hidden, model.head, rows, result)
33
+ return result
34
+
35
+
36
+ @torch.inference_mode()
37
+ def score_blends(baseline, auxiliary, inputs, weights):
38
+ rows = sorted(inputs, key=lambda row:len(row['text']))
39
+ reference = baseline.predict(rows, len(rows))
40
+ predictions = {0.:reference}
41
+ if not any(weights):
42
+ return predictions
43
+ auxiliary.predict(rows, len(rows))
44
+ base_outer, base_names = baseline.count_guidance.last_logits
45
+ extra_outer, extra_names = auxiliary.count_guidance.last_logits
46
+ for weight in weights:
47
+ if not weight:
48
+ continue
49
+ outer = base_outer.lerp(extra_outer, weight)
50
+ names = base_names.lerp(extra_names, weight)
51
+ predictions[weight] = decode_cached_scores(baseline, rows, outer, names)
52
+ return predictions
pytorch/shared/compact_title_acceptance.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare support for an absorbed title span in both frozen extractors."""
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from shared.compact_path_ranker import difference_vector
7
+
8
+
9
+ MERGE_ACTION = 'absorb_fields'
10
+ MINIMUM_POINTER_MARGIN = -3.
11
+
12
+
13
+ @torch.inference_mode()
14
+ def title_merge_signals(rows, baseline, alternatives, models, upper_margin=None):
15
+ pending = [(i,*choices[MERGE_ACTION]) for i,choices in enumerate(alternatives)
16
+ if MERGE_ACTION in choices and MINIMUM_POINTER_MARGIN<choices[MERGE_ACTION][0]
17
+ and (upper_margin is None or choices[MERGE_ACTION][0]<=upper_margin)]
18
+ if not pending:
19
+ return
20
+ evidence = [
21
+ (tuple(value.float().log_softmax(-1).cpu().numpy() for value in model.count_guidance.last_logits),
22
+ model.count_guidance.last_count_logp)
23
+ for model in models
24
+ ]
25
+ for i,margin,candidate in pending:
26
+ length = len(rows[i]['text'])
27
+ signals = [difference_vector(baseline[i],candidate,tuple(score[i,:length] for score in scores),counts[i],0)
28
+ for scores,counts in evidence]
29
+ yield i,candidate,np.concatenate((np.asarray([margin],dtype=np.float32),*signals))
30
+
31
+
32
+ @torch.inference_mode()
33
+ def choose_supported_title_merges(rows, predictions, options, models, selector, threshold):
34
+ alternatives = list(title_merge_signals(rows,predictions,options,models))
35
+ result = list(predictions)
36
+ if alternatives:
37
+ scores = selector(torch.from_numpy(np.stack([signal for _,_,signal in alternatives]))).tolist()
38
+ for (index,proposal,_),score in zip(alternatives,scores,strict=True):
39
+ if score>threshold:
40
+ result[index] = proposal
41
+ return result
pytorch/shared/compact_title_pointer.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score complete title spans from a frozen character representation."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+
7
+ from shared.dataset_schema import visible_value
8
+
9
+
10
+ TITLE_ACTIONS = ('absorb_fields', 'expand', 'shrink')
11
+ TITLE_POINTER_WIDTH = 96
12
+
13
+
14
+ class CompactTitlePointer(nn.Module):
15
+ def __init__(self, width=TITLE_POINTER_WIDTH):
16
+ super().__init__()
17
+ self.character = nn.Linear(192,width)
18
+ self.boundary = nn.Sequential(nn.LayerNorm(3*width+1),nn.Linear(3*width+1,width),nn.GELU())
19
+ self.unary = nn.Linear(width,2)
20
+ self.start_query = nn.Linear(width,32)
21
+ self.end_key = nn.Linear(width,32)
22
+
23
+ def forward(self, hidden, lengths):
24
+ features = self.character(hidden)
25
+ offsets = torch.arange(features.size(1)+1,device=features.device)
26
+ mask = offsets[:-1][None,:] < lengths[:,None]
27
+ features = features * mask[...,None]
28
+ edge = torch.zeros_like(features[:,:1])
29
+ before = torch.cat((edge,features),dim=1)
30
+ after = torch.cat((features,edge),dim=1)
31
+ context = (features.sum(1)/lengths[:,None])[:,None].expand_as(before)
32
+ position = offsets[None,:].expand(hidden.size(0),-1) / lengths[:,None]
33
+ boundary = self.boundary(torch.cat((before,after,context,position[...,None]),dim=-1))
34
+ unary = self.unary(boundary)
35
+ return unary[...,0],unary[...,1],self.start_query(boundary)/np.sqrt(32),self.end_key(boundary)
36
+
37
+
38
+ def boundary_masks(rows, width, device):
39
+ start = np.zeros((len(rows),width),dtype=bool)
40
+ end = np.zeros_like(start)
41
+ for i,row in enumerate(rows):
42
+ visible = [not char.isspace() for char in row['text']]
43
+ length = len(visible)
44
+ start[i,:length] = visible
45
+ end[i,1:length+1] = visible
46
+ return torch.from_numpy(start).to(device),torch.from_numpy(end).to(device)
47
+
48
+
49
+ def title_alternatives(text, baseline, scores, actions=TITLE_ACTIONS):
50
+ titles = [(i,f) for i,f in enumerate(baseline['fields']) if f['label']=='TITLE']
51
+ if len(titles) != 1:
52
+ return {}
53
+ title_index, title = titles[0]
54
+ old_start, old_end = title['start'],title['end']
55
+ other = [(i,f['start'],f['end']) for i,f in enumerate(baseline['fields']) if i!=title_index]
56
+ people = [(p['start'],p['end']) for p in baseline['contributors']]
57
+ left,right,query,key = scores
58
+ starts = np.array([n for n in range(max(0,old_start-12),min(len(text),old_start+13))
59
+ if not text[n].isspace()],dtype=np.int64)
60
+ ends = np.array([n for n in range(max(1,old_end-100),min(len(text),old_end+100)+1)
61
+ if not text[n-1].isspace()],dtype=np.int64)
62
+ if not len(starts) or not len(ends):
63
+ return {}
64
+ values = (left[starts,None]+right[None,ends]+query[starts]@key[ends].T)
65
+ valid = starts[:,None]<ends[None,:]
66
+ # Only propose intervals that overlap the detected title and preserve every contributor.
67
+ valid &= (starts[:,None]<old_end) & (ends[None,:]>old_start)
68
+ for begin,finish in people:
69
+ valid &= (starts[:,None]>=finish) | (ends[None,:]<=begin)
70
+ absorbed = np.zeros_like(valid)
71
+ for _,begin,finish in other:
72
+ overlap = (starts[:,None]<finish) & (ends[None,:]>begin)
73
+ contained = (starts[:,None]<=begin) & (ends[None,:]>=finish)
74
+ valid &= (~overlap | contained)
75
+ absorbed |= contained
76
+ base = float(left[old_start]+right[old_end]+query[old_start]@key[old_end])
77
+ valid &= (starts[:,None]!=old_start) | (ends[None,:]!=old_end)
78
+ expanding = (starts[:,None]<old_start) | (ends[None,:]>old_end)
79
+ variants = {}
80
+ for action,mask in zip(TITLE_ACTIONS,(absorbed,~absorbed & expanding,~absorbed & ~expanding),strict=True):
81
+ if action not in actions:
82
+ continue
83
+ allowed = valid & mask
84
+ if not allowed.any():
85
+ continue
86
+ ranked = np.where(allowed,values,-np.inf)
87
+ i,j = np.unravel_index(ranked.argmax(),ranked.shape)
88
+ start,end = int(starts[i]),int(ends[j])
89
+ dropped = {p for p,a,b in other if start<=a and b<=end}
90
+ result = [f for p,f in enumerate(baseline['fields']) if p!=title_index and p not in dropped]
91
+ result.append({'label':'TITLE','start':start,'end':end,'value':visible_value(text[start:end],'TITLE')})
92
+ result.sort(key=lambda field:field['start'])
93
+ variants[action] = (float(ranked[i,j])-base,{**baseline,'fields':result})
94
+ return variants
95
+
96
+
97
+ @torch.inference_mode()
98
+ def title_comparisons(rows, predictions, hidden, pointer, actions=TITLE_ACTIONS):
99
+ lengths = torch.tensor([len(row['text']) for row in rows],device=hidden.device)
100
+ tensors = pointer(hidden.float(),lengths)
101
+ scores = [tensor.float().cpu().numpy() for tensor in tensors]
102
+ return [title_alternatives(row['text'],pred,tuple(array[i] for array in scores),actions)
103
+ for i,(row,pred) in enumerate(zip(rows,predictions,strict=True))]
104
+
105
+
106
+ def apply_title_comparisons(predictions, alternatives, thresholds):
107
+ adjusted = []
108
+ for baseline,options in zip(predictions,alternatives,strict=True):
109
+ eligible = [(score-thresholds[action],action,proposal) for action,(score,proposal) in options.items()
110
+ if action in thresholds and score>thresholds[action]]
111
+ adjusted.append(max(eligible)[2] if eligible else baseline)
112
+ return adjusted
pytorch/shared/compact_trial_head_storage.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expand a rowwise int8 extraction head in its isolated runtime directory."""
2
+
3
+ from pathlib import Path
4
+
5
+ from safetensors.torch import load_file, save_file
6
+
7
+ from shared.weight_storage import decode_int8_weights
8
+
9
+
10
+ def decode_trial_head(package: Path) -> None:
11
+ head = package/'trial_head.safetensors'
12
+ if head.is_symlink():
13
+ raise ValueError('expected_a_temporary_trial_head')
14
+ decoded = decode_int8_weights(load_file(head))
15
+ temporary = head.with_suffix('.decoded')
16
+ save_file(decoded,temporary)
17
+ temporary.replace(head)
pytorch/shared/compact_version_spans.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distinguish version values from volume values without changing span offsets."""
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from shared.dataset_schema import visible_value
7
+ from shared.field_span_classifier import span_descriptors
8
+
9
+
10
+ @torch.inference_mode()
11
+ def reclassify_version_spans(rows, predictions, hidden, classifier, threshold):
12
+ coordinates, descriptors = [], []
13
+ for i, (source,prediction) in enumerate(zip(rows,predictions,strict=True)):
14
+ if source['id'] != prediction['id']:
15
+ raise ValueError('version_span_prediction_misaligned')
16
+ fields = [(j,field['start'],field['end']) for j,field in enumerate(prediction['fields'])
17
+ if field['label']=='VOLUME']
18
+ if not fields:
19
+ continue
20
+ text = source['text']
21
+ characters = hidden[i,:len(text)].float().cpu().numpy()
22
+ vectors = span_descriptors(characters,[(start,end) for _,start,end in fields],character_width=192)
23
+ coordinates.extend((i,j,start,end) for j,start,end in fields)
24
+ descriptors.extend(vectors)
25
+ if not coordinates:
26
+ return predictions
27
+ result = list(predictions)
28
+ copies = {}
29
+ scores = classifier(torch.from_numpy(np.asarray(descriptors,dtype=np.float32))).tolist()
30
+ for (i,j,start,end), score in zip(coordinates,scores,strict=True):
31
+ if score <= threshold:
32
+ continue
33
+ if i not in copies:
34
+ copies[i] = list(predictions[i]['fields'])
35
+ result[i] = {**predictions[i],'fields':copies[i]}
36
+ original = rows[i]['text'][start:end]
37
+ copies[i][j] = {'label':'VERSION','start':start,'end':end,'value':visible_value(original,'VERSION')}
38
+ return result
pytorch/shared/compact_weight_deltas.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Share identical resources and losslessly store differences between model packages."""
2
+
3
+ from compression import zstd
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+
10
+ from shared.package_resources import RuntimeResources
11
+
12
+
13
+ def resource_contents(package: Path) -> dict[Path, bytes]:
14
+ resources = RuntimeResources(package)
15
+ try:
16
+ return {path.relative_to(resources.path):read_resource(path)
17
+ for path in resources.path.rglob('*') if path.is_file()
18
+ and path.name not in ('runtime_resources.json', 'runtime_resources.tar.zst')}
19
+ finally:
20
+ resources.temporary.cleanup()
21
+
22
+
23
+ def read_resource(path: Path) -> bytes:
24
+ content = path.read_bytes()
25
+ return zstd.decompress(content) if path.name.endswith('.safetensors.zst') else content
26
+
27
+
28
+ def encode_delta(previous: bytes | None, content: bytes, level: int = 9) -> tuple[str, bytes]:
29
+ if previous == content:
30
+ return 'shared', b''
31
+ compressed = zstd.compress(content, level=level)
32
+ if previous is not None and len(previous) == len(content):
33
+ base = np.frombuffer(previous, dtype=np.uint8)
34
+ current = np.frombuffer(content, dtype=np.uint8)
35
+ delta = zstd.compress((current-base).tobytes(), level=level)
36
+ if len(delta) < len(compressed):
37
+ return 'byte_delta', delta
38
+ return 'compressed_full', compressed
39
+
40
+
41
+ def decode_delta(method: str, previous: bytes | None, payload: bytes) -> bytes:
42
+ if method == 'compressed_full':
43
+ return zstd.decompress(payload)
44
+ if previous is None:
45
+ raise ValueError('missing_base_resource')
46
+ if method == 'shared':
47
+ return previous
48
+ if method != 'byte_delta':
49
+ raise ValueError('invalid_resource_encoding')
50
+ delta = zstd.decompress(payload)
51
+ if len(delta) != len(previous):
52
+ raise ValueError('invalid_resource_delta_size')
53
+ return (np.frombuffer(previous, dtype=np.uint8) + np.frombuffer(delta, dtype=np.uint8)).tobytes()
54
+
55
+
56
+ def prepare_delta_model(baseline: dict[Path, bytes], candidate: dict[Path, bytes],
57
+ folder: Path | None = None, level: int = 9) -> dict:
58
+ inventory = {}
59
+ if folder is not None:
60
+ folder.mkdir()
61
+ for index, (path, content) in enumerate(sorted(candidate.items())):
62
+ previous = baseline.get(path)
63
+ method, payload = encode_delta(previous, content, level=level)
64
+ if decode_delta(method, previous, payload) != content:
65
+ raise ValueError(f'resource_delta_failed_roundtrip:{path}')
66
+ entry = {'bytes':len(payload), 'method':method, 'sha256':hashlib.sha256(content).hexdigest()}
67
+ if payload and folder is not None:
68
+ entry['payload'] = f'{index:03d}.zst'
69
+ (folder/entry['payload']).write_bytes(payload)
70
+ inventory[path.as_posix()] = entry
71
+ if folder is not None:
72
+ (folder/'manifest.json').write_text(json.dumps(inventory, sort_keys=True)+'\n')
73
+ return {'resources':inventory, 'removed_resources':sorted(path.as_posix() for path in baseline.keys()-candidate.keys()),
74
+ 'payload_bytes':sum(entry['bytes'] for entry in inventory.values())}
75
+
76
+
77
+ def restore_delta_model(baseline: Path, folder: Path, target: Path) -> None:
78
+ resources = RuntimeResources(baseline)
79
+ try:
80
+ manifest = json.loads((folder/'manifest.json').read_text())
81
+ for name, entry in manifest.items():
82
+ relative = Path(name)
83
+ if relative.is_absolute() or '..' in relative.parts or not relative.name:
84
+ raise ValueError('invalid_delta_resource_path')
85
+ base_path = resources.path/relative
86
+ previous = read_resource(base_path) if base_path.is_file() else None
87
+ payload_name = entry.get('payload')
88
+ if payload_name and Path(payload_name).name != payload_name:
89
+ raise ValueError('invalid_delta_payload_path')
90
+ payload = (folder/payload_name).read_bytes() if payload_name else b''
91
+ if len(payload) != entry['bytes']:
92
+ raise ValueError('invalid_delta_payload_size')
93
+ content = decode_delta(entry['method'], previous, payload)
94
+ if hashlib.sha256(content).hexdigest() != entry['sha256']:
95
+ raise ValueError(f'restored_resource_hash_mismatch:{name}')
96
+ destination = target/relative
97
+ destination.parent.mkdir(parents=True, exist_ok=True)
98
+ if destination.name.endswith('.safetensors.zst'):
99
+ content = zstd.compress(content, level=9)
100
+ with destination.open('xb') as stream:
101
+ stream.write(content)
102
+ finally:
103
+ resources.temporary.cleanup()
pytorch/shared/count_guided_candidates.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """文字ラベルの経路と、原文から推定した項目数で抽出候補を比較する。"""
2
+ from collections import Counter
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ from shared.bibform_trial import FIELDS
8
+ from shared.span_tagger import (OUTER_NAMES,joint_constraint_tables,
9
+ prediction_from_labels,viterbi_paths)
10
+
11
+
12
+ def count_vector(prediction):
13
+ counts=Counter(field['label'] for field in prediction['fields'])
14
+ return np.array([min(counts[label],3) for label in FIELDS],np.int64)
15
+
16
+
17
+ def count_direction(log_probabilities,counts):
18
+ target=log_probabilities.argmax(-1)
19
+ current=log_probabilities[np.arange(len(FIELDS)),counts]
20
+ preferred=log_probabilities[np.arange(len(FIELDS)),target]
21
+ difference=target-counts
22
+ return np.sign(difference)*np.minimum((preferred-current)/np.maximum(np.abs(difference),1),10.)
23
+
24
+
25
+ def decode_candidates(head,outer,names,lengths,inputs,begin_bias=None):
26
+ states,legal,initial,final=joint_constraint_tables()
27
+ outer_ids=torch.tensor([s[0] for s in states],device=outer.device)
28
+ name_ids=torch.tensor([s[1] for s in states],device=outer.device)
29
+ work=outer.float().clone();location=OUTER_NAMES.index('LOCATION')
30
+ work[:,:,1+2*location:3+2*location]=-10000
31
+ original=(work[...,outer_ids]+names.float()[...,name_ids]).cpu()
32
+ if begin_bias is not None:
33
+ starts=torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS],device=outer.device)
34
+ work[:,:,starts]+=begin_bias[:,None,:]
35
+ emissions=(work[...,outer_ids]+names.float()[...,name_ids]).cpu()
36
+ transition=head.outer_transitions[outer_ids[:,None],outer_ids[None,:]]+head.names_transitions[name_ids[:,None],name_ids[None,:]]
37
+ start=head.outer_start[outer_ids]+head.names_start[name_ids]
38
+ end=head.outer_end[outer_ids]+head.names_end[name_ids]
39
+ transition=legal+head.transition_scale*transition.cpu()
40
+ start=initial+head.transition_scale*start.cpu();end=final+head.transition_scale*end.cpu()
41
+ paths=viterbi_paths(emissions,[int(n) for n in lengths],transition,start,end)
42
+ predictions=[];scores=[]
43
+ for i,(row,path) in enumerate(zip(inputs,paths,strict=True)):
44
+ predictions.append(prediction_from_labels(row['id'],row['text'],[states[s][0] for s in path],[states[s][1] for s in path]))
45
+ selected=torch.tensor(path,dtype=torch.long)
46
+ score=original[i,torch.arange(len(path)),selected].double().sum()
47
+ score+=transition[selected[:-1],selected[1:]].double().sum()+start[selected[0]].double()+end[selected[-1]].double()
48
+ scores.append(float(score))
49
+ return predictions,np.array(scores,np.float64)
pytorch/shared/count_guided_predictor.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """文字経路の得点を保ち、学習した項目数で原文だけの抽出候補を選ぶ。"""
2
+ from copy import deepcopy
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ from shared.bibform_trial import FIELDS,signature
8
+ from shared.count_guided_candidates import count_direction,count_vector,decode_candidates
9
+ from shared.span_tagger import OUTER_NAMES
10
+ from shared.global_field_counts import field_start_mass
11
+
12
+
13
+ class CountGuidedPredictor:
14
+ def __init__(self,model,generation_scales,ranking_scale,minimum_gain=.1):
15
+ assert generation_scales and all(np.isfinite(v) and 0<v<=4 for v in generation_scales)
16
+ assert np.isfinite(ranking_scale) and ranking_scale>=0 and np.isfinite(minimum_gain) and minimum_gain>=0
17
+ self.model=model.eval();self.generation_scales=tuple(generation_scales)
18
+ self.ranking_scale=ranking_scale;self.minimum_gain=minimum_gain
19
+ self.capture_logits = False
20
+ self.title_residual = None
21
+ self.title_residual_scale = 0.
22
+
23
+ @torch.inference_mode()
24
+ def predict(self,head,features,lengths,inputs,role_threshold,postprocess):
25
+ assert head.hidden_width==192 and head.label_transitions and head.structure=='unrestricted'
26
+ if head.field_presence_prior:
27
+ hidden,presence=head.encode(features,lengths,inputs,return_presence=True)
28
+ else:hidden=head.encode(features,lengths,inputs)
29
+ outer,names=head.outer(hidden),head.names(hidden)
30
+ soft_mass=field_start_mass(outer,lengths) if self.model.use_soft_mass else None
31
+ if head.field_presence_prior:
32
+ prior=head.field_presence_prior
33
+ odds=torch.tensor(prior['log_prior_odds'],device=outer.device)
34
+ eligible=torch.tensor(prior['eligible'],device=outer.device)
35
+ evidence=(presence[:,:len(FIELDS)]-head.presence_positive_weights[:len(FIELDS)].log()-odds).clamp(-10,10)*eligible
36
+ starts=torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS],device=outer.device)
37
+ outer[:,:,starts]+=prior['scale']*evidence[:,None,:]
38
+ if self.title_residual is not None and self.title_residual_scale:
39
+ outer = self.title_residual.adjust(outer,hidden,lengths,self.title_residual_scale)
40
+ return self.predict_from_scores(head,hidden,outer,names,lengths,inputs,role_threshold,postprocess,soft_mass)
41
+
42
+ @torch.inference_mode()
43
+ def predict_from_scores(self,head,hidden,outer,names,lengths,inputs,role_threshold,postprocess,soft_mass):
44
+ valid=(torch.arange(hidden.shape[1],device=hidden.device)[None,:]<lengths[:,None])[...,None]
45
+ global_features=torch.cat([(hidden*valid).sum(1)/lengths[:,None],hidden.masked_fill(~valid,-torch.inf).amax(1)],-1)
46
+ logp=self.model(global_features,soft_mass).log_softmax(-1).cpu().numpy()
47
+ self.last_count_logp=logp
48
+ self.last_global_features=global_features.cpu().numpy()
49
+ self.last_hidden=hidden.detach()
50
+ if self.capture_logits:
51
+ self.last_logits = (outer.detach(), names.detach())
52
+
53
+ def finish(rows,raw,values,sizes):
54
+ mentions=[(i,p['start'],p['end']) for i,row in enumerate(raw) for p in row['contributors']]
55
+ assigned=head.assign_roles(rows,raw,head.role_scores(values,sizes,mentions),role_threshold)
56
+ return [postprocess(inp['text'],row) for inp,row in zip(rows,assigned,strict=True)]
57
+
58
+ raw,local=decode_candidates(head,outer,names,lengths,inputs)
59
+ baseline=finish(inputs,raw,hidden,lengths)
60
+ counts=np.stack([count_vector(row) for row in baseline])
61
+ directions=np.stack([count_direction(lp,number) for lp,number in zip(logp,counts,strict=True)])
62
+ selected=list(baseline)
63
+ known=[{signature(row)} for row in baseline]
64
+ base_global=np.array([lp[np.arange(len(FIELDS)),number].sum() for lp,number in zip(logp,counts,strict=True)])
65
+ best=local+self.ranking_scale*base_global;original=best.copy()
66
+ affected=np.flatnonzero(np.any(directions!=0,axis=1))
67
+ if not len(affected) or not self.ranking_scale:return selected
68
+ index=torch.tensor(affected,device=hidden.device);rows=[inputs[i] for i in affected]
69
+ for scale in self.generation_scales:
70
+ bias=torch.from_numpy((scale*directions[affected]).astype(np.float32)).to(hidden.device)
71
+ raw,scores=decode_candidates(head,outer[index],names[index],lengths[index],rows,bias)
72
+ candidates=finish(rows,raw,hidden[index],lengths[index])
73
+ for parent,row,score in zip(affected,candidates,scores,strict=True):
74
+ value=signature(row)
75
+ if value in known[parent]:continue
76
+ known[parent].add(value)
77
+ number=count_vector(row);global_score=float(logp[parent,np.arange(len(FIELDS)),number].sum())
78
+ total=score+self.ranking_scale*global_score
79
+ if total>best[parent] and total-original[parent]>self.minimum_gain:
80
+ best[parent]=total;selected[parent]=row
81
+ return selected
pytorch/shared/csl_spans.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CSLが出力した注釈から、表示された項目・人物・姓名の文字範囲を構成する。"""
2
+
3
+ from html.parser import HTMLParser
4
+ from difflib import SequenceMatcher
5
+ import hashlib
6
+ import random
7
+ import re
8
+
9
+ from shared.dataset_schema import RAW_FIELD_NAMES as FIELD_NAMES, stable_seed
10
+ from shared.text_offsets import transform_characters
11
+
12
+
13
+ class AnnotatedHTML(HTMLParser):
14
+ def __init__(self) -> None:
15
+ super().__init__(convert_charrefs=True)
16
+ self.text = ""
17
+ self.stack: list[tuple[str, int]] = []
18
+ self.annotations: list[tuple[str, int, int]] = []
19
+
20
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
21
+ if tag == "mark":
22
+ self.stack.append((dict(attrs)["data-label"], len(self.text)))
23
+
24
+ def handle_endtag(self, tag: str) -> None:
25
+ if tag == "mark":
26
+ label, start = self.stack.pop()
27
+ self.annotations.append((label, start, len(self.text)))
28
+
29
+ def handle_data(self, text: str) -> None:
30
+ self.text += text
31
+
32
+
33
+ def parse_rendered(html: str) -> tuple[str, list[tuple[str, int, int]]]:
34
+ parser = AnnotatedHTML()
35
+ parser.feed(html)
36
+ replacements = []
37
+ previous_space = True
38
+ for char in parser.text:
39
+ space = char.isspace()
40
+ replacements.append("" if space and previous_space else " " if space else char)
41
+ previous_space = space
42
+ text, spans = transform_characters(parser.text, parser.annotations, replacements)
43
+ text = text.rstrip()
44
+ trimmed = []
45
+ for label,start,end in spans:
46
+ end = min(end,len(text))
47
+ while start<end and text[start].isspace(): start+=1
48
+ while end>start and text[end-1].isspace(): end-=1
49
+ if end>start: trimmed.append((label,start,end))
50
+ return text, trimmed
51
+
52
+
53
+ def canonical_annotations(html: str, plain_html: str) -> tuple[str,list[tuple[str,int,int]]]:
54
+ text, annotations = parse_rendered(html)
55
+ plain,_ = parse_rendered(plain_html)
56
+ if text==plain: return text,annotations
57
+ if re.sub(r"[\W_]","",text)!=re.sub(r"[\W_]","",plain):
58
+ raise ValueError("annotation_changed_bibliographic_content")
59
+ starts=[0]*(len(text)+1);ends=[0]*(len(text)+1);inserts=[]
60
+ for operation,i,j,a,b in SequenceMatcher(None,text,plain,autojunk=False).get_opcodes():
61
+ if operation=="insert": inserts.append((i,a,b));continue
62
+ for index in range(i,j+1):
63
+ value=a+(index-i) if operation=="equal" else a+round((index-i)*(b-a)/max(j-i,1))
64
+ starts[index]=ends[index]=value
65
+ for index,a,b in inserts: starts[index]=b;ends[index]=a
66
+ return plain,[(label,starts[left],ends[right]) for label,left,right in annotations if starts[left]<ends[right]]
67
+
68
+
69
+ def make_example(record: dict[str, object], html: str, style: str, split: str, group_id: str, variant: int, *, noisy: bool = False, plain_html: str | None = None) -> dict[str, object]:
70
+ text, annotations = canonical_annotations(html,plain_html) if plain_html is not None else parse_rendered(html)
71
+ if noisy:
72
+ rng = random.Random(stable_seed(record["source_id"]+style+str(variant), 20261110))
73
+ table = {",":",", ";":";", ":":":", "(":"(", ")":")", "[":"[", "]":"]"}
74
+ fullwidth = rng.random()<.65
75
+ replacements = []
76
+ for i,char in enumerate(text):
77
+ value = table.get(char,char) if fullwidth else char
78
+ if char==" " and i>30 and rng.random()<.10: value="\n"
79
+ if char in {"–","—"} and rng.random()<.5: value="-"
80
+ if char==" " and i>0 and text[i-1]=="." and rng.random()<.20: value=""
81
+ replacements.append(value)
82
+ text, annotations = transform_characters(text, annotations, replacements)
83
+ roles={p["role"].upper() for p in record.get("people",[])}
84
+ role_labels={"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"}
85
+ fields = sorted({span for span in annotations if span[0] in FIELD_NAMES and (span[0] not in role_labels or not roles or span[0] in roles)},key=lambda s:(s[1],-s[2]))
86
+ # 日付の書式が年月日を表示しても、既存のYEAR層は表示された年だけを対象にする。
87
+ fields = [(label,start+match.start(),start+match.end()) if label=="YEAR" and (match:=re.search(re.escape(record["year"]),text[start:end])) else (label,start,end)
88
+ for label,start,end in fields]
89
+ selected = []
90
+ for field in fields:
91
+ if selected and field[1]<selected[-1][2]:
92
+ if field[2]<=selected[-1][2]: continue
93
+ raise ValueError("overlapping_csl_fields")
94
+ selected.append(field)
95
+ people = []
96
+ for label,start,end in sorted(annotations,key=lambda s:s[1]):
97
+ if label not in {"PERSON","ORGANIZATION"}: continue
98
+ parents = [f for f in selected if f[0] in {"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"} and f[1]<=start<end<=f[2]]
99
+ if len(parents)!=1: raise ValueError("person_without_unique_role")
100
+ person = {"kind":label,"start":start,"end":end,"role":parents[0][0].lower(),"order":len(people)}
101
+ for part,left,right in annotations:
102
+ if part in {"FAMILY","GIVEN"} and start<=left<right<=end:
103
+ if part.lower() in person: raise ValueError("fragmented_name_part")
104
+ person[part.lower()]={"start":left,"end":right}
105
+ people.append(person)
106
+ omissions=[]
107
+ for role in {p["role"] for p in record.get("people",[])}:
108
+ total=sum(p["role"]==role for p in record["people"])
109
+ shown=sum(p["role"]==role for p in people)
110
+ if shown<total: omissions.append({"role":role,"source_count":total,"visible_count":shown})
111
+ spans = [{"label":label,"start":start,"end":end,"text":text[start:end],
112
+ "utf16_start":len(text[:start].encode("utf-16-le"))//2,"utf16_end":len(text[:end].encode("utf-16-le"))//2} for label,start,end in selected]
113
+ return {"id":hashlib.sha256(f"csl-v2:{record['source_id']}:{split}:{style}:{variant}".encode()).hexdigest()[:24],
114
+ "base_id":record["source_id"],"group_id":group_id,"split":split,"style":style,
115
+ "language":record["language"],"kind":record["kind"],"text":text,"spans":spans,"people":people,
116
+ "omissions":omissions,"source":record["source"],"source_url":record["source_url"],"metadata_terms":record["metadata_terms"],"noisy":noisy}
pytorch/shared/dataset_revision.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """v1を保存したまま、出典付きの書誌修正と区切り空白の学習例を作る。"""
2
+
3
+ from copy import deepcopy
4
+ import re
5
+
6
+ from shared.dataset_schema import validate_target, visible_value
7
+ from shared.text_offsets import transform_characters
8
+
9
+ # 小文字の独立語だけを移す。Van という名や Binard-van のような複合名は推定しない。
10
+ PARTICLE = re.compile(r'^(.*?)\s+((?:van (?:der|den|de)|de (?:la|los|las)|von der|van|von|de|del|der|den|da|di|du))$')
11
+ LIFESPAN = re.compile(r',\s*(?:[12]\d{3})?\s*[-–—]\s*(?:[12]\d{3})?\s*$')
12
+
13
+
14
+ def revise_record(record: dict, reviewed: list[dict]) -> tuple[dict, list[dict]]:
15
+ result = deepcopy(record)
16
+ changes = []
17
+ for correction in reviewed:
18
+ if correction['source_id'] != record['source_id']:
19
+ continue
20
+ current = result
21
+ for key in correction['path'][:-1]:
22
+ current = current[key]
23
+ key = correction['path'][-1]
24
+ if correction.get('operation') == 'add':
25
+ if key in current:
26
+ raise ValueError('reviewed_correction_target_exists:' + record['source_id'])
27
+ if correction['before'] is not None:
28
+ raise ValueError('reviewed_addition_requires_missing_before:' + record['source_id'])
29
+ elif current[key] != correction['before']:
30
+ raise ValueError('reviewed_correction_before_changed:' + record['source_id'])
31
+ current[key] = correction['after']
32
+ changes.append(correction)
33
+ for index, person in enumerate(result['people']):
34
+ if person['literal']:
35
+ continue
36
+ for part in ('family', 'given'):
37
+ before = person[part]
38
+ after = LIFESPAN.sub('', before).strip()
39
+ if after != before and after and re.search(r'\d{4}', before):
40
+ person[part] = after
41
+ changes.append({'source_id':record['source_id'], 'path':['people',index,part],
42
+ 'before':before, 'after':after, 'reason':'氏名末尾に混入した生没年を除去'})
43
+ match = PARTICLE.fullmatch(person['given'])
44
+ if match and match[1] and person['family']:
45
+ before = {'family':person['family'], 'given':person['given']}
46
+ person['given'] = match[1]
47
+ person['family'] = match[2] + ' ' + person['family']
48
+ changes.append({'source_id':record['source_id'], 'path':['people',index], 'before':before,
49
+ 'after':{'family':person['family'], 'given':person['given']},
50
+ 'reason':'独立した小文字の姓の前置詞をfamilyへ統一するv2の姓名方針'})
51
+ if re.match(r'^故\s+', person['family']):
52
+ before = person['family']
53
+ person['family'] = re.sub(r'^故\s+', '', before)
54
+ changes.append({'source_id':record['source_id'], 'path':['people',index,'family'],
55
+ 'before':before, 'after':person['family'], 'reason':'姓に混入した故人の接頭辞を除去'})
56
+ return result, changes
57
+
58
+
59
+ def separator_spacing(text: str, target: dict, new_id: str, variant: int = 0) -> tuple[str, dict]:
60
+ """項目の外の区切りだけへ空白を挿入し、内容と正解の境界を保つ。"""
61
+ spans = [('field:' + str(i), span['start'], span['end']) for i, span in enumerate(target['fields'])]
62
+ for i, person in enumerate(target['contributors']):
63
+ spans.append((f'person:{i}', person['start'], person['end']))
64
+ spans.extend((f'{part}:{i}', span['start'], span['end']) for part, span in person['name_parts'].items())
65
+ occupied = [False] * len(text)
66
+ for _, start, end in spans:
67
+ occupied[start:end] = [True] * (end-start)
68
+ replacements = [('\n' if variant == 1 else ' ') + char
69
+ if char in ':;:;' and not occupied[i] else char for i,char in enumerate(text)]
70
+ changed, moved = transform_characters(text, spans, replacements)
71
+ result = deepcopy(target)
72
+ result['id'] = new_id
73
+ for label,start,end in moved:
74
+ kind, index = label.split(':')
75
+ item = (result['fields'][int(index)] if kind == 'field' else result['contributors'][int(index)]
76
+ if kind == 'person' else result['contributors'][int(index)]['name_parts'][kind])
77
+ item.update(start=start, end=end, value=visible_value(changed[start:end], item.get('label', kind)))
78
+ validate_target(changed, result)
79
+ return changed, result
pytorch/shared/dataset_schema.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """引用文字列から見える情報と、収集メタデータを分離するデータ仕様。"""
2
+
3
+ import hashlib
4
+ from copy import deepcopy
5
+ import random
6
+ import re
7
+ import unicodedata
8
+
9
+ from shared.text_offsets import transform_characters
10
+
11
+
12
+ RAW_FIELD_NAMES=("AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR","TITLE","JOURNAL","BOOKTITLE","YEAR","DATE","VOLUME","ISSUE","PAGES","PUBLISHER","LOCATION","DOI","ISBN","URL","EDITION","VERSION","INSTITUTION")
13
+ FIELD_NAMES=("TITLE","CONTAINER_TITLE","DATE","VOLUME","ISSUE","PAGES","ISSUER","LOCATION","DOI","ISBN","URL","EDITION","VERSION")
14
+ FIELD_MAP={**{name:name for name in FIELD_NAMES},"YEAR":"DATE","JOURNAL":"CONTAINER_TITLE","BOOKTITLE":"CONTAINER_TITLE","PUBLISHER":"ISSUER","INSTITUTION":"ISSUER"}
15
+ SCHEMA_VERSION="bibliography-visible-spans/1"
16
+
17
+
18
+ def stable_seed(value: str, seed: int = 20261110) -> int:
19
+ return int(hashlib.sha256(f"{seed}:{value}".encode()).hexdigest()[:16],16)
20
+
21
+
22
+ def visible_value(text: str,label: str) -> str:
23
+ value=" ".join(text.split())
24
+ return unicodedata.normalize("NFKC",value) if label in {"DOI","URL","ISBN"} else value
25
+
26
+
27
+ def primary_target(sample: dict[str,object]) -> dict[str,object]:
28
+ text=sample["text"];fields=[];contributors=[]
29
+ for span in sample["spans"]:
30
+ if span["label"] in {"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"}:continue
31
+ label=FIELD_MAP[span["label"]];start,end=span["start"],span["end"]
32
+ fields.append({"label":label,"start":start,"end":end,"value":visible_value(text[start:end],label)})
33
+ for person in sample["people"]:
34
+ row={"kind":person["kind"].lower(),"start":person["start"],"end":person["end"],"value":visible_value(text[person["start"]:person["end"]],"CONTRIBUTOR"),"name_parts":{}}
35
+ for part in ("family","given"):
36
+ if part in person:
37
+ start,end=person[part]["start"],person[part]["end"]
38
+ row["name_parts"][part]={"start":start,"end":end,"value":visible_value(text[start:end],part)}
39
+ contributors.append(row)
40
+ result={"id":sample["id"],"fields":fields,"contributors":contributors}
41
+ validate_target(text,result)
42
+ return result
43
+
44
+
45
+ def validate_target(text: str,target: dict[str,object]) -> None:
46
+ previous=0
47
+ for field in target["fields"]:
48
+ if set(field)!={"label","start","end","value"}:raise ValueError("invalid_field_keys")
49
+ if field["label"] not in FIELD_NAMES:raise ValueError("unknown_target_field")
50
+ a,b=field["start"],field["end"]
51
+ if type(a) is not int or type(b) is not int:raise ValueError("offset_must_be_integer")
52
+ if not previous<=a<b<=len(text):raise ValueError("invalid_or_overlapping_target_field")
53
+ previous=b
54
+ if field["value"]!=visible_value(text[a:b],field["label"]):raise ValueError("target_value_not_grounded_in_input")
55
+ previous=0
56
+ for person in target["contributors"]:
57
+ if set(person)!={"kind","start","end","value","name_parts"}:raise ValueError("invalid_contributor_keys")
58
+ a,b=person["start"],person["end"]
59
+ if type(a) is not int or type(b) is not int:raise ValueError("offset_must_be_integer")
60
+ if person["kind"] not in {"person","organization"} or not previous<=a<b<=len(text):raise ValueError("invalid_or_overlapping_contributor")
61
+ previous=b
62
+ if any(f["start"]<b and f["end"]>a for f in target["fields"]):raise ValueError("contributor_overlaps_bibliographic_field")
63
+ if person["value"]!=visible_value(text[a:b],"CONTRIBUTOR"):raise ValueError("contributor_value_not_grounded")
64
+ if (person["kind"]=="organization")!= (not person["name_parts"]):raise ValueError("contributor_kind_name_parts_disagree")
65
+ covered=[]
66
+ for part,span in person["name_parts"].items():
67
+ if set(span)!={"start","end","value"} or type(span["start"]) is not int or type(span["end"]) is not int:raise ValueError("invalid_name_part_keys_or_offsets")
68
+ if part not in {"family","given"} or not a<=span["start"]<span["end"]<=b:raise ValueError("invalid_name_part")
69
+ if any(start<span["end"] and end>span["start"] for start,end in covered):raise ValueError("overlapping_name_parts")
70
+ covered.append((span["start"],span["end"]))
71
+ if span["value"]!=visible_value(text[span["start"]:span["end"]],part):raise ValueError("name_value_not_grounded")
72
+ if set(target)!={"id","fields","contributors"}:raise ValueError("hidden_metadata_in_primary_target")
73
+
74
+
75
+ def target_signature(target: dict[str,object]) -> tuple[object,...]:
76
+ fields=tuple(sorted((f["label"],f["start"],f["end"]) for f in target["fields"]))
77
+ people=tuple(sorted((p["kind"],p["start"],p["end"],tuple(sorted((key,s["start"],s["end"]) for key,s in p["name_parts"].items()))) for p in target["contributors"]))
78
+ return fields,people
79
+
80
+
81
+ def require_identifying_content(target: dict[str,object]) -> None:
82
+ labels={f["label"] for f in target["fields"]}
83
+ if not (labels&{"TITLE","DOI","ISBN","URL"} or ("CONTAINER_TITLE" in labels and labels&{"VOLUME","PAGES"})):
84
+ raise ValueError("citation_without_title_identifier_or_container_locator")
85
+
86
+
87
+ def script_profile(text: str) -> dict[str,int]:
88
+ return {"japanese_characters":sum("\u3040"<=c<="\u30ff" or "\u3400"<=c<="\u9fff" for c in text),"latin_characters":sum("LATIN" in unicodedata.name(c,"") for c in text),"characters":len(text)}
89
+
90
+
91
+ def bio_labels(length: int,spans: list[tuple[str,int,int]],names: tuple[str,...]) -> list[int]:
92
+ result=[0]*length
93
+ for label,start,end in spans:
94
+ if label not in names or not 0<=start<end<=length or any(result[start:end]):raise ValueError("invalid_or_overlapping_bio_span")
95
+ index=1+2*names.index(label);result[start]=index
96
+ for position in range(start+1,end):result[position]=index+1
97
+ return result
98
+
99
+
100
+ def formatting_noise(text: str,target: dict[str,object],seed: int,new_id: str) -> tuple[str,dict[str,object]]:
101
+ rng=random.Random(seed);replacements=[];fullwidth={",":",",":":":",";":";","(":"(",")":")"}
102
+ for char in text:
103
+ value=char
104
+ if char==" ":
105
+ number=rng.random()
106
+ if number<.07:value="\n"
107
+ elif number<.10:value=" "
108
+ elif char in fullwidth and rng.random()<.30:value=fullwidth[char]
109
+ elif char in "–—" and rng.random()<.5:value="-"
110
+ replacements.append(value)
111
+ if "".join(replacements)==text:
112
+ position=next((i for i,c in enumerate(text) if c==" "),None)
113
+ if position is not None:replacements[position]="\n"
114
+ annotations=[("field:"+str(i),s["start"],s["end"]) for i,s in enumerate(target["fields"])]
115
+ for index,person in enumerate(target["contributors"]):
116
+ annotations.append((f"person:{index}",person["start"],person["end"]))
117
+ for part,span in person["name_parts"].items():annotations.append((f"{part}:{index}",span["start"],span["end"]))
118
+ changed,spans=transform_characters(text,annotations,replacements);result=deepcopy(target);result["id"]=new_id
119
+ for label,start,end in spans:
120
+ kind,index=label.split(":");index=int(index)
121
+ item=result["fields"][index] if kind=="field" else result["contributors"][index] if kind=="person" else result["contributors"][index]["name_parts"][kind]
122
+ item.update(start=start,end=end)
123
+ value_label=item["label"] if kind=="field" else kind
124
+ item["value"]=visible_value(changed[start:end],value_label)
125
+ def content(value: str) -> str:return "".join(unicodedata.normalize("NFKC",value).translate(str.maketrans({"–":"-","—":"-"})).split())
126
+ if content(changed)!=content(text):raise ValueError("noise_changed_bibliographic_content")
127
+ validate_target(changed,result)
128
+ return changed,result
pytorch/shared/date_qualifier.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """認識済みの日付へ隣接する説明語を、他の抽出範囲に重ならない場合だけ含める。"""
2
+
3
+ from copy import deepcopy
4
+ from functools import lru_cache
5
+ import re
6
+
7
+ from shared.dataset_schema import visible_value
8
+
9
+
10
+ @lru_cache(maxsize=16)
11
+ def qualifier_pattern(phrases: tuple[str, ...]) -> re.Pattern:
12
+ alternatives = [r'\s+'.join(re.escape(word) for word in phrase.split())
13
+ for phrase in sorted(phrases, key=len, reverse=True)]
14
+ return re.compile(r'(?<![A-Za-z])(?:' + '|'.join(alternatives) + r')\s*', re.I)
15
+
16
+
17
+ def extend_date_qualifiers(text: str, prediction: dict, phrases: list[str]) -> dict:
18
+ result = deepcopy(prediction)
19
+ if not phrases:
20
+ return result
21
+ pattern = qualifier_pattern(tuple(phrases))
22
+ for index, field in enumerate(result['fields']):
23
+ if field['label'] != 'DATE':
24
+ continue
25
+ start, end = field['start'], field['end']
26
+ offset = max(0, start - 64)
27
+ window = text[offset:min(end, start + 64)]
28
+ candidates = [offset + match.start() for match in pattern.finditer(window)
29
+ if offset + match.start() < start <= offset + match.end() < end]
30
+ if not candidates:
31
+ continue
32
+ revised = min(candidates)
33
+ protected = [f for i, f in enumerate(result['fields']) if i != index] + result['contributors']
34
+ if any(revised < span['end'] and span['start'] < start for span in protected):
35
+ continue
36
+ field.update(start=revised, value=visible_value(text[revised:end], 'DATE'))
37
+ return result
pytorch/shared/doi_volume_prior.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """訓練書誌で確認したDOIの数値構造から、既知の巻と異なる年の誤分類を補助する。"""
2
+
3
+ from copy import deepcopy
4
+ import re
5
+
6
+
7
+ def doi_numbers(value: str) -> tuple[str, str, list[re.Match]] | None:
8
+ match = re.fullmatch(r'(10\.\d{4,9})/(.+)', value.casefold())
9
+ if match is None:
10
+ return None
11
+ suffix = match[2]
12
+ numbers = list(re.finditer(r'\d+', suffix))
13
+ if not numbers:
14
+ return None
15
+ # 数字の前後の記号まで一致する系列だけをまとめる。
16
+ key = match[1] + '/' + re.sub(r'\d+', '#', suffix)
17
+ return key, suffix, numbers
18
+
19
+
20
+ def inferred_volume(doi: str, rules: dict) -> str | None:
21
+ parts = doi_numbers(doi)
22
+ if parts is None:
23
+ return None
24
+ key, suffix, numbers = parts
25
+ rule = rules.get(key)
26
+ if rule is None:
27
+ return None
28
+ value = suffix[numbers[rule['begin']].start():numbers[rule['end']].end()]
29
+ return value if value in rule['observed_volumes'] else None
30
+
31
+
32
+ def apply_doi_volume_prior(prediction: dict, rules: dict) -> dict:
33
+ result = deepcopy(prediction)
34
+ volumes = {value for field in prediction['fields'] if field['label'] == 'DOI'
35
+ if (value := inferred_volume(field['value'], rules)) is not None}
36
+ if len(volumes) != 1:
37
+ return result
38
+ volume = next(iter(volumes))
39
+ years = {match[0] for field in prediction['fields'] if field['label'] == 'DATE'
40
+ for match in re.finditer(r'(?<!\d)(?:1[5-9]|20)\d{2}(?!\d)', field['value'])}
41
+ for field in result['fields']:
42
+ if field['label'] == 'VOLUME' and field['value'] in years and field['value'] != volume:
43
+ field['label'] = 'DATE'
44
+ return result
pytorch/shared/field_fragments.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """同一項目の隣接した断片だけを、固定した接続条件で合わせる。"""
2
+ from copy import deepcopy
3
+ import re
4
+ from shared.dataset_schema import visible_value
5
+
6
+
7
+ def merge_field_fragments(text: str, prediction: dict, rules: list[dict]) -> dict:
8
+ result = deepcopy(prediction)
9
+ merged = []
10
+ for field in result['fields']:
11
+ previous = merged[-1] if merged else None
12
+ if previous and previous['label'] == field['label']:
13
+ gap = text[previous['end']:field['start']]
14
+ applicable = any(rule['label'] == field['label'] and re.fullmatch(rule['gap_pattern'], gap) for rule in rules)
15
+ protected = any(previous['end'] < p['end'] and p['start'] < field['start'] for p in result['contributors'])
16
+ if applicable and not protected:
17
+ previous.update(end=field['end'], value=visible_value(text[previous['start']:field['end']], field['label']))
18
+ continue
19
+ merged.append(field)
20
+ result['fields'] = merged
21
+ return result
pytorch/shared/field_span_classifier.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """固定した3補助モデルの文字表現から、候補範囲の項目種別と不採用を判定する。"""
2
+ from collections import Counter
3
+ from copy import deepcopy
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+
9
+ from shared.bibform_trial import FIELDS,validate
10
+ from shared.dataset_schema import visible_value
11
+
12
+
13
+ DESCRIPTOR_WIDTH=4*576+3
14
+
15
+
16
+ def span_descriptors(characters:np.ndarray,spans:list[tuple[int,int]],character_width:int=576) -> np.ndarray:
17
+ assert character_width in (192,576)
18
+ values=np.asarray(characters[:,:192] if character_width==192 else characters[:,192:768],dtype=np.float32)
19
+ assert values.ndim==2 and values.shape[1]==character_width and len(values)>0
20
+ bounds=np.asarray(spans,dtype=np.int64).reshape(-1,2)
21
+ assert np.all(bounds[:,0]>=0) and np.all(bounds[:,1]<=len(values)) and np.all(bounds[:,1]>bounds[:,0])
22
+ prefix=np.concatenate([np.zeros((1,character_width),dtype=np.float32),values.cumsum(0,dtype=np.float32)])
23
+ start,end=bounds[:,0],bounds[:,1]
24
+ length=end-start
25
+ geometry=np.stack([start/len(values),end/len(values),np.log1p(length)/np.log1p(len(values))],-1).astype(np.float32)*4
26
+ return np.concatenate([values[start],values[end-1],(prefix[end]-prefix[start])/length[:,None],
27
+ np.broadcast_to(values.mean(0),(len(spans),character_width)),geometry],-1).astype(np.float16)
28
+
29
+
30
+ class FieldSpanClassifier(nn.Module):
31
+ def __init__(self,width:int=64,neural_context_width:int=0,character_width:int=576):
32
+ super().__init__()
33
+ assert neural_context_width in (0,384)
34
+ self.neural_context_width=neural_context_width
35
+ assert character_width in (192,576)
36
+ self.character_width=character_width
37
+ input_width=4*character_width+3+neural_context_width
38
+ self.network=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,width),
39
+ nn.GELU(),nn.Dropout(.1),nn.Linear(width,len(FIELDS)+1))
40
+
41
+ def forward(self,descriptors:torch.Tensor) -> torch.Tensor:
42
+ return self.network(descriptors)
43
+
44
+
45
+ def append_neural_context(descriptors:np.ndarray,context:np.ndarray) -> np.ndarray:
46
+ assert descriptors.ndim==2 and descriptors.shape[1] in (DESCRIPTOR_WIDTH,771) and context.shape==(384,)
47
+ return np.concatenate([descriptors,np.broadcast_to(context.astype(np.float16),(len(descriptors),384))],-1).astype(np.float16)
48
+
49
+
50
+ def overlaps(left:tuple[int,int],right:tuple[int,int]) -> bool:
51
+ return left[0]<right[1] and right[0]<left[1]
52
+
53
+
54
+ def candidate_spans(text:str,baseline:dict,index:int) -> list[tuple[int,int]]:
55
+ field=baseline['fields'][index];start,end=field['start'],field['end']
56
+ variants={(start,end)}
57
+ variants.update((start+delta,end) for delta in (-4,-3,-2,-1,1,2,3,4))
58
+ variants.update((start,end+delta) for delta in (-4,-3,-2,-1,1,2,3,4))
59
+ variants.update((start+delta,end+delta) for delta in (-4,-2,-1,1,2,4))
60
+ blockers=[(f['start'],f['end']) for i,f in enumerate(baseline['fields']) if i!=index]
61
+ blockers.extend((p['start'],p['end']) for p in baseline['contributors'])
62
+ return sorted(span for span in variants if 0<=span[0]<span[1]<=len(text)
63
+ and not text[span[0]].isspace() and not text[span[1]-1].isspace()
64
+ and not any(overlaps(span,other) for other in blockers))
65
+
66
+
67
+ def apply_proposals(text:str,original:dict,proposals:list,minimum_gain:float,
68
+ count_logp:np.ndarray|None=None,count_scale:float=0.) -> dict:
69
+ row=deepcopy(original);changed=set()
70
+ for gain,index,label,start,end in sorted(proposals,reverse=True):
71
+ if gain<=minimum_gain:break
72
+ if index in changed:continue
73
+ if count_logp is not None and count_scale:
74
+ counts=Counter(field['label'] for field in row['fields'])
75
+ before=np.array([min(counts[field],3) for field in FIELDS])
76
+ counts[row['fields'][index]['label']]-=1;counts[label]+=1
77
+ after=np.array([min(counts[field],3) for field in FIELDS])
78
+ count_gain=float((count_logp[np.arange(len(FIELDS)),after]-count_logp[np.arange(len(FIELDS)),before]).sum())
79
+ if gain+min(0.,count_scale*count_gain)<=minimum_gain:continue
80
+ blocked=any(overlaps((start,end),(f['start'],f['end'])) for i,f in enumerate(row['fields']) if i!=index)
81
+ if blocked:continue
82
+ row['fields'][index]={'label':label,'start':start,'end':end,'value':visible_value(text[start:end],label)};changed.add(index)
83
+ row['fields'].sort(key=lambda f:(f['start'],f['end'],f['label']))
84
+ return row
85
+
86
+
87
+ class FieldSpanRefiner:
88
+ def __init__(self,model:FieldSpanClassifier,minimum_gain:float,count_scale:float=0.,boundary_only:bool=False):
89
+ assert np.isfinite(minimum_gain) and minimum_gain>=0 and np.isfinite(count_scale) and count_scale>=0
90
+ self.model=model.cpu().eval();self.minimum_gain=minimum_gain
91
+ self.count_scale=count_scale;self.boundary_only=boundary_only
92
+
93
+ @torch.inference_mode()
94
+ def proposals(self,characters:np.ndarray,inp:dict,original:dict,neural_context:np.ndarray|None=None) -> list:
95
+ options=[candidate_spans(inp['text'],original,i) for i in range(len(original['fields']))]
96
+ spans=sorted({span for candidates in options for span in candidates})
97
+ if not spans:return []
98
+ positions={span:i for i,span in enumerate(spans)}
99
+ descriptors=span_descriptors(characters,spans,self.model.character_width)
100
+ if self.model.neural_context_width:
101
+ assert neural_context is not None
102
+ descriptors=append_neural_context(descriptors,neural_context)
103
+ logp=self.model(torch.from_numpy(descriptors.astype(np.float32))).log_softmax(-1).numpy()
104
+ proposals=[]
105
+ for index,(field,candidates) in enumerate(zip(original['fields'],options,strict=True)):
106
+ old=(field['start'],field['end']);old_label=1+FIELDS.index(field['label'])
107
+ before=logp[positions[old],old_label]
108
+ for start,end in candidates:
109
+ for label_index,label in enumerate(FIELDS,1):
110
+ if self.boundary_only and label!=field['label']:continue
111
+ movement=abs(start-old[0])+abs(end-old[1])
112
+ gain=float(logp[positions[start,end],label_index]-before)-.1*movement-.25*(label!=field['label'])
113
+ if gain>.25:proposals.append((gain,index,label,start,end))
114
+ return proposals
115
+
116
+ @torch.inference_mode()
117
+ def predict(self,features:torch.Tensor,inputs:list[dict],predictions:list[dict],count_logp:np.ndarray|None=None,
118
+ neural_context:np.ndarray|None=None) -> list[dict]:
119
+ characters=features[:,:,:768].detach().cpu().numpy()
120
+ assert not self.count_scale or count_logp is not None
121
+ assert not self.model.neural_context_width or neural_context is not None
122
+ result=[]
123
+ for row_index,(inp,original) in enumerate(zip(inputs,predictions,strict=True)):
124
+ assert inp['id']==original['id']
125
+ proposals=self.proposals(characters[row_index,:len(inp['text'])],inp,original,
126
+ neural_context[row_index] if neural_context is not None else None)
127
+ revised=apply_proposals(inp['text'],original,proposals,self.minimum_gain,
128
+ count_logp[row_index] if count_logp is not None else None,self.count_scale)
129
+ validate(inp['text'],revised);result.append(revised)
130
+ return result
131
+
132
+
pytorch/shared/frozen_character_features.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """保存した抽出器の文字表現を取得し、範囲予測層へ渡す。原文だけを入力する。"""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from safetensors.torch import load_file
6
+ import torch
7
+
8
+ from shared.range_extraction import build_range_head,prediction_from_ranges
9
+ from shared.span_tagger import EncodedCitation,load_package
10
+
11
+
12
+ class RangePredictor:
13
+ def __init__(self,package: Path,device: str) -> None:
14
+ self.device=device
15
+ self.model,self.tokenizer,self.config=load_package(package,device)
16
+ self.range_config=json.loads((package/'range_model.json').read_text())
17
+ self.head=build_range_head(self.range_config['architecture'],192*len(self.model.members)).to(device)
18
+ self.head.load_state_dict(load_file(package/'range_head.safetensors',device=device));self.head.eval()
19
+ self.features={};self.handles=[]
20
+ for index,member in enumerate(self.model.members):
21
+ def capture(module: object,args: tuple,i: int=index) -> None:self.features[i]=args[0].detach()
22
+ self.handles.append(member.heads[0].register_forward_pre_hook(capture))
23
+
24
+ @torch.inference_mode()
25
+ def predict(self,inputs: list[dict],batch_size: int=16) -> list[dict]:
26
+ if any(set(row)!={'id','text'} or not isinstance(row['id'],str) or not isinstance(row['text'],str) or not row['text'] for row in inputs):raise ValueError('only_nonempty_id_text_inputs_allowed')
27
+ if len({r['id'] for r in inputs})!=len(inputs):raise ValueError('duplicate_input_id')
28
+ ordered=sorted(inputs,key=lambda row:len(row['text']));predictions={}
29
+ for begin in range(0,len(ordered),batch_size):
30
+ chunk=ordered[begin:begin+batch_size]
31
+ rows=[EncodedCitation(r['id'],r['text'],[0],[],[],[],None) for r in chunk]
32
+ self.model.member_text_outputs(rows,self.device)
33
+ # キャッシュ学習と実行時で、文字表現の保存精度を同じにする。
34
+ maximum=max(len(r['text']) for r in chunk)
35
+ features=torch.cat([self.features[i][:,:maximum] for i in range(len(self.model.members))],dim=-1).half().float()
36
+ lengths=torch.tensor([len(r['text']) for r in chunk],device=self.device)
37
+ options={'texts':[r['text'] for r in chunk]} if getattr(self.head,'needs_text',False) else {}
38
+ ranges=self.head.extract(features,lengths,float(self.range_config['threshold']),**options)
39
+ for row,spans in zip(chunk,ranges,strict=True):predictions[row['id']]=prediction_from_ranges(row['id'],row['text'],spans)
40
+ return [predictions[r['id']] for r in inputs]
pytorch/shared/global_field_counts.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """原文から得た引用全体の表現で、表示項目の個数を予測する。"""
2
+ import torch
3
+ from torch import nn
4
+
5
+ from shared.bibform_trial import FIELDS
6
+ from shared.span_tagger import OUTER_NAMES
7
+
8
+
9
+ def field_start_mass(outer, lengths):
10
+ """項目開始の確率を原文の有効文字だけで合計する。"""
11
+ logits=outer.float().clone()
12
+ location=OUTER_NAMES.index('LOCATION')
13
+ logits[...,1+2*location:3+2*location]=-10000
14
+ starts=[1+2*OUTER_NAMES.index(label) for label in FIELDS]
15
+ valid=torch.arange(outer.shape[1],device=outer.device)[None,:]<lengths[:,None]
16
+ return (logits.softmax(-1)[...,starts]*valid[...,None]).sum(1).log1p()
17
+
18
+
19
+ class GlobalFieldCounts(nn.Module):
20
+ def __init__(self, use_soft_mass=False):
21
+ super().__init__()
22
+ self.use_soft_mass=use_soft_mass
23
+ self.network=nn.Sequential(nn.LayerNorm(384),nn.Linear(384,128),nn.GELU(),
24
+ nn.Dropout(.1),nn.Linear(128,len(FIELDS)*4))
25
+ if use_soft_mass:
26
+ self.mass_residual=nn.Sequential(nn.Linear(len(FIELDS),32),nn.GELU(),nn.Linear(32,len(FIELDS)*4))
27
+ nn.init.zeros_(self.mass_residual[-1].weight)
28
+ nn.init.zeros_(self.mass_residual[-1].bias)
29
+
30
+ def forward(self,features,soft_mass=None):
31
+ logits=self.network(features)
32
+ if self.use_soft_mass:
33
+ if soft_mass is None:raise ValueError('field_start_mass_required')
34
+ logits=logits+self.mass_residual(soft_mass)
35
+ return logits.reshape(-1,len(FIELDS),4)
36
+
37
+ @torch.no_grad()
38
+ def initialize(self,source,frequencies,warm):
39
+ if warm:
40
+ for index in (0,1):self.network[index].load_state_dict(source.global_presence_head[index].state_dict())
41
+ previous=source.global_presence_head[3]
42
+ self.network[4].weight.zero_();self.network[4].bias.zero_()
43
+ conditional=(frequencies[:,1:]+.5)/(frequencies[:,1:].sum(-1,keepdim=True)+1.5)
44
+ for label in range(len(FIELDS)):
45
+ for count in range(1,4):
46
+ self.network[4].weight[label*4+count]=previous.weight[label]
47
+ self.network[4].bias[label*4+count]=(previous.bias[label]
48
+ -source.presence_positive_weights[label].log()+conditional[label,count-1].log())
49
+ else:
50
+ self.network[4].weight.zero_()
51
+ self.network[4].bias.copy_(((frequencies+.5)/(frequencies.sum(-1,keepdim=True)+2)).log().flatten())
pytorch/shared/inference_strategies.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """原文に対する固定抽出器の得点を、辞書を使わずに統合する。"""
2
+ from copy import deepcopy
3
+
4
+ import torch
5
+ from torch import Tensor
6
+
7
+
8
+ def combine_scores(outputs: list[list[Tensor]], weights: Tensor, settings: dict) -> list[Tensor]:
9
+ from shared.span_tagger import combine_ensemble_logits
10
+ mode = settings.get('fusion', 'logits')
11
+ if mode == 'logits':
12
+ return combine_ensemble_logits(outputs, weights)
13
+ normalized = weights / weights.sum(1, keepdim=True)
14
+ result = []
15
+ temperature = float(settings.get('temperature', 1.))
16
+ if temperature <= 0:
17
+ raise ValueError('positive_fusion_temperature_required')
18
+ for head in range(2):
19
+ scores = [values[head].float() for values in outputs]
20
+ own_weights = [normalized[head, i] if normalized.ndim == 2 else normalized[head, i, :, None, None]
21
+ for i in range(len(scores))]
22
+ if mode == 'probabilities':
23
+ values = [(value / temperature).softmax(-1) for value in scores]
24
+ merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)).clamp_min(1e-12).log()
25
+ # 温度を変える比較でも、姓名得点との相対尺度は元へ戻す。
26
+ merged = merged * temperature
27
+ elif mode == 'standardized_logits':
28
+ values = [(value - value.mean(-1, keepdim=True)) / value.std(-1, keepdim=True, correction=0).clamp_min(.1)
29
+ for value in scores]
30
+ reference = sum(value.std(-1, keepdim=True, correction=0) * weight
31
+ for value, weight in zip(scores, own_weights, strict=True)).clamp_min(.1)
32
+ merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)) * reference
33
+ elif mode == 'votes':
34
+ values = [torch.nn.functional.one_hot(value.argmax(-1), value.shape[-1]).float() for value in scores]
35
+ merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)) * float(settings.get('vote_scale', 8.))
36
+ elif mode == 'median_logits':
37
+ values = [value - value.mean(-1, keepdim=True) for value in scores]
38
+ merged = torch.stack(values).median(0).values
39
+ else:
40
+ raise ValueError('unknown_score_fusion:' + mode)
41
+ result.append(merged)
42
+ if settings.get('scope', 'outer') == 'outer':
43
+ result[1] = combine_ensemble_logits(outputs, weights)[1]
44
+ return result
45
+
46
+
47
+ def structural_predictions(logits: list[Tensor], rows: list, name_weight: float, settings: dict) -> list[dict]:
48
+ from shared.span_tagger import OUTER_NAMES, decode_predictions, joint_constraint_tables, prediction_from_labels, viterbi_paths
49
+ base = decode_predictions(logits, rows, 'joint', name_weight)
50
+ constraint = settings.get('structure')
51
+ if not constraint:
52
+ return base
53
+ if constraint != 'single_title':
54
+ raise ValueError('unknown_structure_constraint')
55
+ title_begin = 1 + 2 * OUTER_NAMES.index('TITLE')
56
+ title_inside = title_begin + 1
57
+ # 既に条件を満たす引用の解は、探索空間を狭めても変わらない。
58
+ selected = [i for i, pred in enumerate(base) if sum(f['label'] == 'TITLE' for f in pred['fields']) > 1]
59
+ if not selected:
60
+ return base
61
+ states, transitions, start, end = joint_constraint_tables()
62
+ size = len(states)
63
+ title = torch.tensor([a in (title_begin, title_inside) for a, _, _ in states])
64
+ augmented = torch.full((2 * size, 2 * size), -torch.inf)
65
+ for seen in (0, 1):
66
+ for before in range(size):
67
+ for after in range(size):
68
+ if title[after] and (seen or (states[after][0] == title_begin and title[before])):
69
+ continue
70
+ closed = seen or (bool(title[before]) and not bool(title[after]))
71
+ augmented[seen * size + before, int(closed) * size + after] = transitions[before, after]
72
+ starts = torch.cat((start, torch.full_like(start, -torch.inf)))
73
+ ends = end.repeat(2)
74
+ index = torch.tensor(selected, device=logits[0].device)
75
+ outer_ids = torch.tensor([a for a, _, _ in states], device=logits[0].device)
76
+ name_ids = torch.tensor([n for _, n, _ in states], device=logits[0].device)
77
+ emissions = logits[0][index][..., outer_ids].float() + name_weight * logits[1][index][..., name_ids].float()
78
+ lengths = [len(rows[i].text) for i in selected]
79
+ paths = viterbi_paths(emissions.repeat(1, 1, 2), lengths, augmented, starts, ends)
80
+ result = deepcopy(base)
81
+ for i, path in zip(selected, paths, strict=True):
82
+ outer = [states[s % size][0] for s in path]
83
+ names = [states[s % size][1] for s in path]
84
+ result[i] = prediction_from_labels(rows[i].identifier, rows[i].text, outer, names)
85
+ return result
86
+
87
+
88
+ def predict_from_outputs(outputs: list[list[Tensor]], weights: Tensor, rows: list,
89
+ calibrator: object | None, settings: dict, name_weight: float = 1.) -> list[dict]:
90
+ from shared.span_tagger import preserve_baseline_structure
91
+ if settings.get('consensus'):
92
+ return consensus_predictions(outputs, weights, rows, calibrator, settings, name_weight)
93
+ own_name_weight = float(settings.get('name_weight', name_weight))
94
+ logits = combine_scores(outputs, weights, settings)
95
+ decoded = structural_predictions(logits, rows, own_name_weight, settings)
96
+ if settings.get('lock_name_structure'):
97
+ return fixed_mention_names(outputs, logits, decoded, rows, calibrator, settings, own_name_weight)
98
+ if calibrator is not None and settings.get('name_cnn', True):
99
+ correction = calibrator.correct(outputs, [row.text for row in rows])
100
+ scale = float(settings.get('name_cnn_scale', 1.))
101
+ corrected = [value + scale * delta for value, delta in zip(logits, correction, strict=True)]
102
+ if settings.get('lock_cnn_outer_scores'):
103
+ corrected[0] = logits[0]
104
+ changed = structural_predictions(corrected, rows, own_name_weight, settings)
105
+ decoded = [preserve_baseline_structure(before, after) for before, after in zip(decoded, changed, strict=True)]
106
+ if settings.get('merge_title_fragments'):
107
+ from shared.field_fragments import merge_field_fragments
108
+ rules = [{'label': 'TITLE', 'gap_pattern': r'[\s.::;;\-–—]*'}]
109
+ decoded = [merge_field_fragments(row.text, pred, rules) for row, pred in zip(rows, decoded, strict=True)]
110
+ return decoded
111
+
112
+
113
+ def fixed_mention_names(outputs: list[list[Tensor]], logits: list[Tensor], baseline: list[dict], rows: list,
114
+ calibrator: object | None, settings: dict, name_weight: float) -> list[dict]:
115
+ from shared.dataset_schema import bio_labels
116
+ from shared.span_tagger import OUTER_NAMES, citation_script_group, decode_predictions, preserve_baseline_structure
117
+ names = logits[1].clone()
118
+ if settings.get('name_routing') == 'mention':
119
+ profiles = settings['name_profiles']
120
+ if len(outputs) != 4 or len(profiles) != 2 or any(len(p) != 4 or sum(p) <= 0 for p in profiles):
121
+ raise ValueError('mention_routing_requires_two_valid_four_member_profiles')
122
+ for i, (row, prediction) in enumerate(zip(rows, baseline, strict=True)):
123
+ for person in prediction['contributors']:
124
+ if person['kind'] != 'person':
125
+ continue
126
+ start, end = person['start'], person['end']
127
+ profile = profiles[citation_script_group(row.text[start:end])]
128
+ total = sum(profile)
129
+ names[i, start:end] = sum(outputs[m][1][i, start:end].float() * (weight / total)
130
+ for m, weight in enumerate(profile))
131
+ if calibrator is not None and settings.get('name_cnn', True):
132
+ names = names + float(settings.get('name_cnn_scale', 1.)) * calibrator.correct(outputs, [r.text for r in rows])[1]
133
+ forced = torch.full_like(logits[0], -torch.inf)
134
+ for i, (row, prediction) in enumerate(zip(rows, baseline, strict=True)):
135
+ spans = [(f['label'], f['start'], f['end']) for f in prediction['fields']]
136
+ spans += [(p['kind'], p['start'], p['end']) for p in prediction['contributors']]
137
+ labels = torch.tensor(bio_labels(len(row.text), spans, OUTER_NAMES), device=forced.device)
138
+ forced[i, torch.arange(len(row.text), device=forced.device), labels] = 0.
139
+ changed = decode_predictions([forced, names], rows, 'joint', name_weight)
140
+ return [preserve_baseline_structure(before, after) for before, after in zip(baseline, changed, strict=True)]
141
+
142
+
143
+ def choose_consensus(candidates: list[dict], references: list[dict], weights: list[list[float]], mode: str) -> dict:
144
+ """正解を参照せず、固定抽出器間での範囲の一致だけを使って候補を選ぶ。"""
145
+ def entities(row: dict) -> tuple[set, set, set]:
146
+ return ({(f['label'], f['start'], f['end']) for f in row['fields']},
147
+ {(p['kind'], p['start'], p['end']) for p in row['contributors']},
148
+ {(k, v['start'], v['end']) for p in row['contributors'] for k, v in p['name_parts'].items()})
149
+
150
+ def agreement(a: set, b: set) -> float:
151
+ return 2 * len(a & b) / (len(a) + len(b)) if a or b else 1.
152
+
153
+ evidence = [entities(row) for row in references]
154
+ own_weights = [[.25] * 4] * 2 if mode == 'uniform' else weights
155
+ best, best_score = candidates[0], -1.
156
+ for candidate in candidates:
157
+ parts = entities(candidate)
158
+ score = 0.
159
+ for i, other in enumerate(evidence):
160
+ score += own_weights[0][i] * (2 * agreement(parts[0], other[0]) + agreement(parts[1], other[1]))
161
+ if mode == 'full':
162
+ score += own_weights[1][i] * agreement(parts[2], other[2])
163
+ if score > best_score + 1e-10:
164
+ best, best_score = candidate, score
165
+ from shared.span_tagger import preserve_baseline_structure
166
+ return deepcopy(best) if mode == 'full' else preserve_baseline_structure(best, candidates[0])
167
+
168
+
169
+ def consensus_predictions(outputs: list[list[Tensor]], weights: Tensor, rows: list,
170
+ calibrator: object | None, settings: dict, name_weight: float) -> list[dict]:
171
+ if len(outputs) != 4:
172
+ raise ValueError('consensus_requires_four_fixed_extractors')
173
+ base_settings = {k: v for k, v in settings.items() if k != 'consensus'}
174
+ pools = [predict_from_outputs(outputs, weights, rows, calibrator, base_settings, name_weight)]
175
+ singles = []
176
+ for i in range(4):
177
+ own = predict_from_outputs([outputs[i]], torch.ones_like(weights[:, :1]), rows, None, {'name_cnn': False}, name_weight)
178
+ singles.append(own)
179
+ members = [j for j in range(4) if j != i]
180
+ leave_out = predict_from_outputs([outputs[j] for j in members], weights[:, members], rows, None,
181
+ {'name_cnn': False}, name_weight)
182
+ pools.extend((own, leave_out))
183
+ normalized = (weights / weights.sum(1, keepdim=True)).float().cpu()
184
+ result = []
185
+ for index in range(len(rows)):
186
+ profile = normalized if normalized.ndim == 2 else normalized[:, :, index]
187
+ result.append(choose_consensus([pool[index] for pool in pools], [single[index] for single in singles],
188
+ profile.tolist(), settings['consensus']))
189
+ return result
pytorch/shared/kbest_viterbi.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Return the best distinct paths through a small first-order state lattice."""
2
+ import torch
3
+ from torch import Tensor
4
+
5
+
6
+ def kbest_viterbi(emissions: Tensor, lengths: list[int], transitions: Tensor,
7
+ initial: Tensor, final: Tensor, k: int) -> list[list[list[int]]]:
8
+ values = emissions.float().cpu()
9
+ batch, steps, states = values.shape
10
+ if k < 1 or len(lengths) != batch or not lengths or min(lengths) < 1 or max(lengths) > steps:
11
+ raise ValueError('invalid_kbest_dimensions')
12
+ transitions, initial, final = transitions.float().cpu(), initial.float().cpu(), final.float().cpu()
13
+ scores = values.new_full((batch, states, k), -torch.inf)
14
+ scores[:, :, 0] = values[:, 0] + initial
15
+ lengths_cpu = torch.as_tensor(lengths)
16
+ back_pointers = []
17
+ for position in range(1, max(lengths)):
18
+ candidates = scores[..., None] + transitions[None, :, None, :]
19
+ best, prior = candidates.reshape(batch, states*k, states).topk(k, dim=1)
20
+ proposed = best.transpose(1,2) + values[:, position, :, None]
21
+ scores = torch.where((lengths_cpu > position)[:, None, None], proposed, scores)
22
+ back_pointers.append(prior.transpose(1,2).numpy())
23
+ scores, endpoints = (scores + final[None, :, None]).reshape(batch,-1).topk(k, dim=1)
24
+ finite = torch.isfinite(scores).tolist()
25
+ all_paths = []
26
+ for row, (length, ends) in enumerate(zip(lengths, endpoints.tolist(), strict=True)):
27
+ own = []
28
+ for rank, index in enumerate(ends):
29
+ if not finite[row][rank]:
30
+ continue
31
+ state, lane = divmod(index,k)
32
+ path = [state]
33
+ for position in range(length-2,-1,-1):
34
+ state, lane = divmod(int(back_pointers[position][row,state,lane]),k)
35
+ path.append(state)
36
+ own.append(list(reversed(path)))
37
+ all_paths.append(own)
38
+ return all_paths
pytorch/shared/name_boundary_prior.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """訓練資料の姓・名の頻度と文字連鎖から、既存の人物範囲内の区切りを補助する。"""
2
+
3
+ from collections import Counter
4
+ from copy import deepcopy
5
+ from functools import lru_cache
6
+ import hashlib
7
+ import math
8
+ import re
9
+ import unicodedata
10
+
11
+ import numpy as np
12
+
13
+ from shared.dataset_schema import visible_value
14
+ from shared.training_lexicon import normalize_with_offsets
15
+
16
+ PARTS = ('family', 'given')
17
+ JAPANESE = re.compile(r'[\u3040-\u30ff\u3400-\u9fff]')
18
+ SEPARATORS = ' ,,、・·\t\n\r'
19
+
20
+
21
+ def normalize_part(value: str) -> str:
22
+ return re.sub(r'\s+', '', unicodedata.normalize('NFKC', value).casefold())
23
+
24
+
25
+ def person_fold(family: str, given: str) -> int:
26
+ key = normalize_part(family) + '\0' + normalize_part(given)
27
+ return int(hashlib.sha256(key.encode()).hexdigest()[:16], 16) % 5
28
+
29
+
30
+ def character_pairs(value: str) -> list[str]:
31
+ value = '^' + normalize_part(value) + '$'
32
+ return [value[i:i + 2] for i in range(len(value) - 1)]
33
+
34
+
35
+ def build_prior(people: set[tuple[str, str]]) -> dict:
36
+ """人物単位の固定fold=0を集計から除き、同一人物の重複を数えない。"""
37
+ selected = {(normalize_part(f), normalize_part(g)) for f, g in people
38
+ if f and g and person_fold(f, g) != 0}
39
+ tables = {}
40
+ for index, part in enumerate(PARTS):
41
+ counts = Counter(pair[index] for pair in selected)
42
+ grams = Counter(gram for pair in selected for gram in character_pairs(pair[index]))
43
+ prefix = Counter()
44
+ for gram, count in grams.items():
45
+ prefix[gram[0]] += count
46
+ tables[part] = {'counts': dict(sorted(counts.items())), 'bigrams': dict(sorted(grams.items())),
47
+ 'prefix': dict(sorted(prefix.items())), 'vocabulary': len({v[-1] for v in grams}) + 1}
48
+ return {'schema': 'bibliography-name-boundary-prior/1', 'people': len(selected),
49
+ 'excluded_person_fold': 0, 'tables': tables}
50
+
51
+
52
+ def prior_value(text: str, signature: tuple[int, int, int, int], prior: dict, character_weight: float) -> float:
53
+ score = 0.
54
+ for index, part in enumerate(PARTS):
55
+ a, b = signature[index * 2:index * 2 + 2]
56
+ value = normalize_part(text[a:b])
57
+ table = prior['tables'][part]
58
+ score += math.log1p(table['counts'].get(value, 0))
59
+ if character_weight:
60
+ grams = character_pairs(value)
61
+ logp = sum(math.log((table['bigrams'].get(gram, 0) + .1) /
62
+ (table['prefix'].get(gram[0], 0) + .1 * table['vocabulary'])) for gram in grams)
63
+ score += character_weight * logp / len(grams)
64
+ return score
65
+
66
+
67
+ def relative_signature(person: dict) -> tuple[int, int, int, int] | None:
68
+ parts = person['name_parts']
69
+ if person['kind'] != 'person' or set(parts) != set(PARTS):
70
+ return None
71
+ return tuple(parts[part][edge] - person['start'] for part in PARTS for edge in ('start', 'end'))
72
+
73
+
74
+ @lru_cache(maxsize=100000)
75
+ def partitions(text: str) -> tuple[tuple[int, int, int, int], ...]:
76
+ """空白のない和文も分割するが、連続したラテン文字の途中では切らない。"""
77
+ found = set()
78
+ if not 2 <= len(text) <= 96:
79
+ return ()
80
+ for cut in range(1, len(text)):
81
+ if all((char.isalpha() or char in "'’") and not JAPANESE.search(char) for char in text[cut - 1:cut + 1]):
82
+ continue
83
+ left_a, left_b, right_a, right_b = 0, cut, cut, len(text)
84
+ while left_a < left_b and text[left_a] in SEPARATORS:
85
+ left_a += 1
86
+ while left_b > left_a and text[left_b - 1] in SEPARATORS:
87
+ left_b -= 1
88
+ while right_a < right_b and text[right_a] in SEPARATORS:
89
+ right_a += 1
90
+ while right_b > right_a and text[right_b - 1] in SEPARATORS:
91
+ right_b -= 1
92
+ if left_a == left_b or right_a == right_b:
93
+ continue
94
+ found.add((left_a, left_b, right_a, right_b))
95
+ found.add((right_a, right_b, left_a, left_b))
96
+ return tuple(sorted(found))
97
+
98
+
99
+ def emission_value(scores: np.ndarray, signature: tuple[int, int, int, int]) -> float:
100
+ tags = np.zeros(len(scores), dtype=np.int64)
101
+ for index in (0, 1):
102
+ a, b = signature[index * 2:index * 2 + 2]
103
+ tags[a] = index * 2 + 1
104
+ tags[a + 1:b] = index * 2 + 2
105
+ return float(scores[np.arange(len(scores)), tags].sum(dtype=np.float64))
106
+
107
+
108
+ def alternatives(text: str, person: dict, scores: np.ndarray, prior: dict,
109
+ character_weight: float, protected: set[str]) -> list[tuple[tuple[int, int, int, int], float, float]]:
110
+ original = relative_signature(person)
111
+ if original is None:
112
+ return []
113
+ value = text[person['start']:person['end']]
114
+ if normalize_with_offsets(value)[0] in protected:
115
+ return []
116
+ candidates = partitions(value)
117
+ if not candidates:
118
+ return []
119
+ base = emission_value(scores, original)
120
+ base_prior = prior_value(value, original, prior, character_weight)
121
+ return [(signature, emission_value(scores, signature) - base,
122
+ prior_value(value, signature, prior, character_weight) - base_prior)
123
+ for signature in candidates if signature != original]
124
+
125
+
126
+ def apply_name_boundary_prior(text: str, prediction: dict, scores: np.ndarray,
127
+ prior: dict, settings: dict, protected: set[str]) -> dict:
128
+ result = deepcopy(prediction)
129
+ if settings['strength'] == 0:
130
+ return result
131
+ for person in result['contributors']:
132
+ start, end = person['start'], person['end']
133
+ choices = alternatives(text, person, scores[start:end], prior, settings['character_weight'], protected)
134
+ if not choices:
135
+ continue
136
+ signature, emission, evidence = max(choices, key=lambda v: v[1] + settings['strength'] * v[2])
137
+ # 新しい分割を正当化する統計的根拠がある場合に限り変更する。
138
+ if evidence <= 0 or emission + settings['strength'] * evidence <= settings['margin']:
139
+ continue
140
+ person['name_parts'] = {part: {'start': start + signature[i * 2], 'end': start + signature[i * 2 + 1],
141
+ 'value': visible_value(text[start + signature[i * 2]:start + signature[i * 2 + 1]], part)}
142
+ for i, part in enumerate(PARTS)}
143
+ return result
144
+
145
+
146
+ def merge_name_corrections(baseline: dict, first: dict, second: dict) -> dict:
147
+ """独立した姓名補正を合わせ、二つの補正が食い違う人物は元の区切りを保つ。"""
148
+ result = deepcopy(baseline)
149
+ proposals = [{(p['kind'], p['start'], p['end']): p['name_parts'] for p in row['contributors']}
150
+ for row in (first, second)]
151
+ for person in result['contributors']:
152
+ if person['kind'] != 'person':
153
+ continue
154
+ key = person['kind'], person['start'], person['end']
155
+ original = person['name_parts']
156
+ a, b = [values.get(key, original) for values in proposals]
157
+ if a == b or b == original:
158
+ person['name_parts'] = deepcopy(a)
159
+ elif a == original:
160
+ person['name_parts'] = deepcopy(b)
161
+ return result
pytorch/shared/name_context_cnn.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """原文の文字と文脈表現から、人物内の姓名ラベルを補正する小さなCNN。"""
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from copy import deepcopy
6
+
7
+ from shared.dataset_schema import visible_value
8
+ from shared.span_tagger import NAME_NAMES,OUTER_NAMES,bio_spans,joint_constraint_tables
9
+
10
+
11
+ def name_context_features(text:str,hidden:np.ndarray,logits:np.ndarray,start:int,end:int,
12
+ context:int=4) -> tuple[np.ndarray,np.ndarray,int,int]:
13
+ assert 0<=start<end<=len(text) and hidden.shape==(len(text),192) and logits.shape==(len(text),5)
14
+ left=max(0,start-context);right=min(len(text),end+context)
15
+ positions=np.arange(left,right)
16
+ geometry=np.stack([(positions-start)/max(1,end-start),(positions>=start)&(positions<end)],-1).astype(np.float32)
17
+ values=np.concatenate([hidden[left:right],logits[left:right],geometry],-1).astype(np.float16)
18
+ encoded=np.zeros((right-left,4),dtype=np.int64)
19
+ for i,char in enumerate(text[left:right]):
20
+ raw=char.encode('utf-8');encoded[i,:len(raw)]=np.frombuffer(raw,dtype=np.uint8).astype(np.int64)+1
21
+ return values,encoded,start-left,end-left
22
+
23
+
24
+ class NameContextCNN(nn.Module):
25
+ def __init__(self,width:int=32):
26
+ super().__init__();self.width=width
27
+ self.bytes=nn.Embedding(257,4,padding_idx=0)
28
+ self.norm=nn.LayerNorm(199)
29
+ self.conv1=nn.Conv1d(215,width,3,padding=1)
30
+ self.conv2=nn.Conv1d(width,width,3,padding=1)
31
+ self.output=nn.Conv1d(width,5,1)
32
+ self.dropout=nn.Dropout(.1)
33
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
34
+
35
+ def forward(self,features:torch.Tensor,raw_bytes:torch.Tensor,lengths:torch.Tensor) -> torch.Tensor:
36
+ valid=torch.arange(features.shape[1],device=features.device)[None,:]<lengths[:,None]
37
+ mask=valid[:,None,:]
38
+ embedded=self.bytes(raw_bytes).flatten(-2)
39
+ values=torch.cat([self.norm(features),embedded],-1).transpose(1,2)*mask
40
+ values=self.dropout(torch.nn.functional.gelu(self.conv1(values)))*mask
41
+ values=self.dropout(torch.nn.functional.gelu(self.conv2(values)))*mask
42
+ return features[...,192:197]+self.output(values).transpose(1,2)
43
+
44
+
45
+ def person_name_labels(person:dict) -> np.ndarray:
46
+ labels=np.zeros(person['end']-person['start'],dtype=np.int64)
47
+ for name,part in person['name_parts'].items():
48
+ start,end=part['start']-person['start'],part['end']-person['start']
49
+ label=1+2*NAME_NAMES.index(name);labels[start:end]=label+1;labels[start]=label
50
+ return labels
51
+
52
+
53
+ def parts_from_name_labels(text:str,person:dict,labels:np.ndarray) -> dict:
54
+ parts={}
55
+ for name,start,end in bio_spans(labels.tolist(),NAME_NAMES):
56
+ a,b=start+person['start'],end+person['start']
57
+ parts[name]={'start':a,'end':b,'value':visible_value(text[a:b],name)}
58
+ assert parts and len(parts)<=2
59
+ return parts
60
+
61
+
62
+ class NamePathDecoder:
63
+ def __init__(self,transitions:torch.Tensor,start:torch.Tensor,end:torch.Tensor,scale:float):
64
+ states,legal,initial,final=joint_constraint_tables()
65
+ begin=1+2*OUTER_NAMES.index('person')
66
+ selected=[i for i,state in enumerate(states) if state[0] in (begin,begin+1)]
67
+ own=[states[i] for i in selected]
68
+ self.names=np.array([state[1] for state in own])
69
+ self.begin=np.array([state[0]==begin for state in own])
70
+ self.learned=transitions.detach().float().cpu().numpy()*scale
71
+ self.start=start.detach().float().cpu().numpy()*scale
72
+ self.end=end.detach().float().cpu().numpy()*scale
73
+ self.transitions=legal[selected][:,selected].numpy()+self.learned[self.names[:,None],self.names[None,:]]
74
+ self.final=final[selected].numpy()
75
+
76
+ def decode(self,logits:np.ndarray,at_start:bool=False,at_end:bool=False) -> np.ndarray:
77
+ assert logits.ndim==2 and logits.shape[1]==5 and len(logits)>0
78
+ initial=self.start if at_start else self.learned[0]
79
+ final=self.end if at_end else self.learned[:,0]
80
+ scores=logits[0,self.names]+initial[self.names]+np.where(self.begin,0.,-10000.)
81
+ history=[]
82
+ for values in logits[1:]:
83
+ candidates=scores[:,None]+self.transitions
84
+ previous=candidates.argmax(0);history.append(previous)
85
+ scores=candidates[previous,np.arange(len(previous))]+values[self.names]+np.where(self.begin,-10000.,0.)
86
+ current=int(np.argmax(scores+self.final+final[self.names]));path=[current]
87
+ for previous in reversed(history):current=int(previous[current]);path.append(current)
88
+ return self.names[np.array(list(reversed(path)))]
89
+
90
+ def score(self,logits:np.ndarray,path:np.ndarray,at_start:bool=False,at_end:bool=False) -> float:
91
+ initial=self.start if at_start else self.learned[0]
92
+ final=self.end if at_end else self.learned[:,0]
93
+ return float(logits[np.arange(len(path)),path].sum()+initial[path[0]]+final[path[-1]]+
94
+ self.learned[path[:-1],path[1:]].sum())
95
+
96
+
97
+ class NameContextRefiner:
98
+ def __init__(self,model:NameContextCNN,head:nn.Module,residual_scale:float,minimum_gain:float):
99
+ assert residual_scale>0 and minimum_gain>=0
100
+ self.model=model.cpu().eval();self.scale=residual_scale;self.minimum_gain=minimum_gain
101
+ self.decoder=NamePathDecoder(head.names_transitions,head.names_start,head.names_end,head.transition_scale)
102
+
103
+ @torch.inference_mode()
104
+ def predict(self,hidden:torch.Tensor,head:nn.Module,inputs:list[dict],predictions:list[dict]) -> list[dict]:
105
+ characters=hidden.detach().float().cpu().numpy()
106
+ name_logits=head.names(hidden).float().cpu().numpy()
107
+ persons=[]
108
+ for row_number,(inp,predicted) in enumerate(zip(inputs,predictions,strict=True)):
109
+ assert inp['id']==predicted['id']
110
+ for person_number,person in enumerate(predicted['contributors']):
111
+ if person['kind']!='person':continue
112
+ features,raw_bytes,start,end=name_context_features(inp['text'],characters[row_number,:len(inp['text'])],
113
+ name_logits[row_number,:len(inp['text'])],person['start'],person['end'])
114
+ persons.append((row_number,person_number,features,raw_bytes,start,end))
115
+ result=list(predictions);changed=set()
116
+ for begin in range(0,len(persons),256):
117
+ rows=persons[begin:begin+256];longest=max(len(row[2]) for row in rows)
118
+ features=np.zeros((len(rows),longest,199),np.float32);raw=np.zeros((len(rows),longest,4),np.int64);lengths=[]
119
+ for i,row in enumerate(rows):
120
+ length=len(row[2]);lengths.append(length);features[i,:length]=row[2];raw[i,:length]=row[3]
121
+ values=torch.from_numpy(features)
122
+ residuals=(self.model(values,torch.from_numpy(raw),torch.tensor(lengths))-values[...,192:197]).numpy()
123
+ for i,(row_number,person_number,_,_,start,end) in enumerate(rows):
124
+ inp=inputs[row_number];person=predictions[row_number]['contributors'][person_number]
125
+ residual=residuals[i,start:end];base=name_logits[row_number,person['start']:person['end']]
126
+ old=person_name_labels(person);mixed=base+self.scale*residual
127
+ at_start=person['start']==0;at_end=person['end']==len(inp['text'])
128
+ path=self.decoder.decode(mixed,at_start,at_end)
129
+ if np.array_equal(old,path):continue
130
+ positions=np.arange(len(old))
131
+ if float((residual[positions,path]-residual[positions,old]).sum())<=0:continue
132
+ gain=self.decoder.score(mixed,path,at_start,at_end)-self.decoder.score(mixed,old,at_start,at_end)
133
+ if gain<=self.minimum_gain:continue
134
+ if row_number not in changed:result[row_number]=deepcopy(predictions[row_number]);changed.add(row_number)
135
+ result[row_number]['contributors'][person_number]['name_parts']=parts_from_name_labels(inp['text'],person,path)
136
+ return result