ブラウザ対応の軽量版を追加
Browse filesPyTorchとONNX、ブラウザ版ZIP、実行例と評価結果を収録
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- LICENSEAdded+202
- NOTICE.mdAdded+9
- README.mdAdded+60
- bibform-lite-web.zipAdded+3
- evaluation.jsonAdded+40
- examples/input.jsonlAdded+2
- licenses/ONNX-Runtime-MIT.txtAdded+21
- licenses/ONNX-Runtime-ThirdPartyNotices.txtAdded
- onnx/byte-network.onnxAdded+3
- onnx/model.jsonAdded+2425
- onnx/role-network.onnxAdded+3
- pytorch/byte_architecture.jsonAdded+6
- pytorch/byte_extractor.safetensorsAdded+3
- pytorch/predict.pyAdded+89
- pytorch/requirements.txtAdded+5
- pytorch/resource_type.jsonAdded+38
- pytorch/resource_type.safetensorsAdded+3
- pytorch/resource_type_model.pyAdded+166
- pytorch/resource_type_raw.jsonAdded+27
- pytorch/resource_type_raw.safetensorsAdded+3
- pytorch/shared/__init__.pyAdded+1
- pytorch/shared/bibform_trial.pyAdded+225
- pytorch/shared/bibform_trial_adapters.pyAdded+85
- pytorch/shared/bibform_trial_model.pyAdded+750
- pytorch/shared/compact_byte_extractor.pyAdded+62
- pytorch/shared/compact_character_proxy.pyAdded+40
- pytorch/shared/compact_edition_endpoint.pyAdded+77
- pytorch/shared/compact_model_selector.pyAdded+105
- pytorch/shared/compact_path_ranker.pyAdded+139
- pytorch/shared/compact_score_blend.pyAdded+52
- pytorch/shared/compact_title_acceptance.pyAdded+41
- pytorch/shared/compact_title_pointer.pyAdded+112
- pytorch/shared/compact_trial_head_storage.pyAdded+17
- pytorch/shared/compact_version_spans.pyAdded+38
- pytorch/shared/compact_weight_deltas.pyAdded+103
- pytorch/shared/count_guided_candidates.pyAdded+49
- pytorch/shared/count_guided_predictor.pyAdded+81
- pytorch/shared/csl_spans.pyAdded+116
- pytorch/shared/dataset_revision.pyAdded+79
- pytorch/shared/dataset_schema.pyAdded+128
- pytorch/shared/date_qualifier.pyAdded+37
- pytorch/shared/doi_volume_prior.pyAdded+44
- pytorch/shared/field_fragments.pyAdded+21
- pytorch/shared/field_span_classifier.pyAdded+132
- pytorch/shared/frozen_character_features.pyAdded+40
- pytorch/shared/global_field_counts.pyAdded+51
- pytorch/shared/inference_strategies.pyAdded+189
- pytorch/shared/kbest_viterbi.pyAdded+38
- pytorch/shared/name_boundary_prior.pyAdded+161
- pytorch/shared/name_context_cnn.pyAdded+136
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789# Bibform
Copyright 2026 Bibform contributors
Bibformの自作部分はApache License 2.0で提供します。
ブラウザ版にはONNX Runtime Web 1.31.1を同梱しています。ONNX Runtime WebのMITライセンスと同版の第三者表示は `licenses/` にあります。
[ONNX Runtimeの出典](https://github.com/microsoft/onnxruntime/releases/tag/v1.31.1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960---license: apache-2.0language: - ja - entags: - bibliography - biblatex - local-inference---
# Bibform Lite
日本語・英語の参考文献の引用原文から、題名・年・掲載先などの書誌項目、人物・団体、姓・名の文字範囲、著者・編者・訳者などの役割、資料種別を推定します。
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.
PyTorchの推論一式は6.00 MBです。[もう一方のモデル](https://huggingface.co/sasakiy84/bibform)も利用できます。
## ブラウザで使う
[ブラウザ版のZIP](bibform-lite-web.zip)を展開し、そのディレクトリを静的ファイルとして配信します。ローカルで試す場合は、展開先で次を実行して `http://127.0.0.1:8000/` を開きます。静的ホストでも同じファイルを使えます。
```bashpython -m http.server 8000 --bind 127.0.0.1```
初回にモデルと実行エンジンを読み込んだ後は、ブラウザ内で引用の解析、種別の選択、BibLaTeXのプレビューと `.bib` の保存ができます。スコアが0.90未満のときは上位3候補と全種別の一覧から選べます。
ONNXモデル一式は5.97 MB、実行エンジンと画面も含む静的配布一式は9.68 MB、ZIPは9.26 MBです。[ONNXと設定](onnx/)、[ブラウザ実装のソース](web-src/)も収録しています。
Chromiumで比較した開発128件では、書誌項目・姓名・役割の出力がPyTorch版と128件で一致しました。接続を切った状態での解析とダウンロードも確認しています。
## Pythonで使う
Python 3.14の環境で、取得したリポジトリのルートから実行します。
```bashpython -m pip install -r pytorch/requirements.txtpython pytorch/predict.py --model pytorch --inputs examples/input.jsonl --output predictions.jsonl --device cpu```
入力は1行に1件の引用を入れたUTF-8のJSONLです。各行に照合用の `id` と引用原文の `text` を指定します。入力例は [examples/input.jsonl](examples/input.jsonl) にあります。
出力の `fields` と `contributors` は、引用原文上の半開区間 `[start, end)` で文字範囲を表します。位置はUnicodeコードポイント単位です。 `resource_type` に元の12種別の首位とスコア、 `resource_type.biblatex` に出力用9種別の候補と自動選択結果が入ります。 `selected` が `null` の場合は候補から種別を選べます。
## 精度と評価条件
bibformDatasetTrial v1-quality14の未知書式の開発10,130件を評価しました。抽出完全一致は、書誌項目・人物や団体・姓名の範囲と役割を含みます。種別はBibLaTeX用9種別で採点しました。資料種別のスコアは分類器の出力を合算した値です。
| 実行方式 | 抽出完全一致 | 種別正解率 | 抽出と種別の完全一致 || --- | ---: | ---: | ---: || PyTorch | 86.07%(8,719件) | 91.17%(9,236件) | 79.40%(8,043件) || ONNX Runtime CPU | 86.16%(8,728件) | 91.15%(9,234件) | 79.47%(8,050件) |
開発データは実在する書誌メタデータを書式に沿って描画した引用です。公開値はこの開発データでの成績です。短い引用や掲載先が曖昧な引用では、題名の範囲や資料種別を取り違える場合があります。 [集計の詳細](evaluation.json)
## ライセンス
Bibformの自作部分には [Apache License 2.0](LICENSE) を適用します。同梱する第三者の配布物とその条件は [NOTICE.md](NOTICE.md) を参照してください。123version https://git-lfs.github.com/spec/v1oid sha256:4c79d7e1aeb4b7baf3922d32bbfde336f009cb0260defbcd48f260e09134b7b1size 925524112345678910111213141516171819202122232425262728293031323334353637383940{ "dataset": "bibformDatasetTrial v1-quality14", "split": "unknown_style_development", "test_opened": false, "pytorch": { "extraction": { "count": 10130, "correct": 8719, "accuracy": 0.86071076011846 }, "merged_score_9": { "count": 10130, "correct": 9236, "accuracy": 0.9117472852912142 }, "joint_9": { "count": 10130, "correct": 8043, "accuracy": 0.7939782823297137 } }, "onnxruntime_cpu": { "count": 10130, "same_extraction": 10088, "same_12_type": 10123, "extraction_exact": 8728, "type_9_exact": 9234, "joint_9_exact": 8050 }, "chromium": { "cases": 128, "same_python_output": 128, "median_ms": 75.19999980926514, "p95_ms": 172.30000019073486, "download": "reference.bib", "assetRequests": 8, "offlineInference": true, "manualChoices": 3 }}12{"id":"example-en","text":"Taylor, J. (2023). Urban rainfall. Example Journal, 4(2), 11–24."}{"id":"example-ja","text":"山田太郎(2024)「海辺の植物」架空研究誌、4巻2号、11–24頁。"}123456789101112131415161718192021MIT License
Copyright (c) Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123version https://git-lfs.github.com/spec/v1oid sha256:7a953c3ab5826334cb0b47c528291b888179d2666654d74775f7904a210aad03size 58319451234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425{ "outer_labels": [ "TITLE", "CONTAINER_TITLE", "DATE", "VOLUME", "ISSUE", "PAGES", "ISSUER", "LOCATION", "DOI", "ISBN", "URL", "EDITION", "VERSION", "person", "organization" ], "name_labels": [ "family", "given" ], "fields": [ "TITLE", "CONTAINER_TITLE", "DATE", "VOLUME", "ISSUE", "PAGES", "ISSUER", "DOI", "ISBN", "URL", "EDITION", "VERSION" ], "roles": [ "author.work", "editor.work", "translator.work", "author.container", "editor.container", "translator.container" ], "type_labels": [ "authored_book", "book_chapter", "conference_paper", "dataset", "edited_book", "journal_article", "proceedings", "report", "software", "thesis", "translated_book", "web" ], "export_types": { "journal_article": "article", "authored_book": "book", "edited_book": "collection", "translated_book": "book", "book_chapter": "incollection", "proceedings": "proceedings", "conference_paper": "inproceedings", "thesis": "thesis", "report": "misc", "dataset": "misc", "software": "misc", "web": "online" }, "ngrams": [ 2, 3, 4, 5 ], "buckets": 32768, "states": [ [ 0, 0, 0 ], [ 1, 0, 0 ], [ 2, 0, 0 ], [ 3, 0, 0 ], [ 4, 0, 0 ], [ 5, 0, 0 ], [ 6, 0, 0 ], [ 7, 0, 0 ], [ 8, 0, 0 ], [ 9, 0, 0 ], [ 10, 0, 0 ], [ 11, 0, 0 ], [ 12, 0, 0 ], [ 13, 0, 0 ], [ 14, 0, 0 ], [ 15, 0, 0 ], [ 16, 0, 0 ], [ 17, 0, 0 ], [ 18, 0, 0 ], [ 19, 0, 0 ], [ 20, 0, 0 ], [ 21, 0, 0 ], [ 22, 0, 0 ], [ 23, 0, 0 ], [ 24, 0, 0 ], [ 25, 0, 0 ], [ 26, 0, 0 ], [ 29, 0, 0 ], [ 30, 0, 0 ], [ 27, 0, 0 ], [ 27, 1, 1 ], [ 27, 3, 2 ], [ 28, 0, 0 ], [ 28, 0, 1 ], [ 28, 1, 1 ], [ 28, 2, 1 ], [ 28, 0, 2 ], [ 28, 3, 2 ], [ 28, 4, 2 ], [ 28, 0, 3 ], [ 28, 1, 3 ], [ 28, 2, 3 ], [ 28, 3, 3 ], [ 28, 4, 3 ] ], "transitions": [ [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0 ], [ -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, -10000.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, 0.0 ], [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, 0.0, -10000.0, -10000.0, -10000.0, 0.0 ] ], "start": [ 0.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, -10000.0, 0.0, 0.0, 0.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0, -10000.0 ], "end": [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -10000.0, 0.0, 0.0, -10000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ], "source_inventory_sha256": "0d4b06f98a343f20adbdeca8499680e050cd7c70bd884b1fbf6a03ccdb6d6188", "packed_initializers": { "byte": 205, "role": 7 }}123version https://git-lfs.github.com/spec/v1oid sha256:029d9fde693486dd86c24f5031d2223e217e12e2c03a864a5db1f1440ff2fa97size 110656123456{ "width": 192, "attention_layers": 14, "parameters": 4656225, "weights_format": "int8"}123version https://git-lfs.github.com/spec/v1oid sha256:eac58cb50520d169ca5f8349c9ed058b2b91ff8c35452ec0eae56c74b481e2c9size 48002401234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Run the independent byte extractor in a standalone package."""
import argparseimport jsonfrom pathlib import Path
from safetensors.torch import load_fileimport torchfrom resource_type_model import ResourceTypeOutput, TypeFieldCountEvidence, pool_context
from shared.compact_byte_extractor import CompactByteExtractorfrom shared.weight_storage import decode_int8_weights
def predict(model,rows,device,batch_size,classifier): ordered = sorted(rows,key=lambda row:len(row['text'])) outputs,position = {},0 while position<len(ordered): end = position+1 while end<len(ordered) and end-position<batch_size and (end-position+1)*len(ordered[end]['text'])**2<=1_400_000: end += 1 raw = ordered[position:end] context = [] if classifier.uses_context: lengths = torch.tensor([len(row['text']) for row in raw], device=device)
def capture(_module, inputs, logits): context.append(pool_context(inputs[0], lengths, logits)) if classifier.field_scale: from shared.bibform_trial import FIELDS from shared.span_tagger import OUTER_NAMES starts = [1 + 2 * OUTER_NAMES.index(label) for label in FIELDS] updated = logits.clone() updated[:, :, starts] += classifier.field_evidence(context[0], len(FIELDS))[:, None, :] return updated
hook = model.head.outer.register_forward_hook(capture) try: extracted = model.predict(raw, device) finally: hook.remove() if len(context) != 1: raise ValueError('expected_one_resource_type_feature_batch') else: extracted = model.predict(raw, device) typed = classifier.attach(raw, extracted, context[0] if context else None) outputs.update((row['id'],row) for row in typed) position = end return [outputs[row['id']] for row in rows]
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--model',type=Path,required=True) parser.add_argument('--inputs',type=Path,required=True) parser.add_argument('--output',type=Path,required=True) parser.add_argument('--device',choices=('cpu','cuda'),default='cuda' if torch.cuda.is_available() else 'cpu') parser.add_argument('--batch-size',type=int,default=48) args = parser.parse_args() if args.batch_size<1: parser.error('positive batch size required') torch.set_num_threads(1) torch.backends.cuda.matmul.allow_tf32 = False rows = [json.loads(line) for line in args.inputs.read_text().splitlines()] 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 rows): raise ValueError('only_nonempty_original_id_and_text_are_accepted') if len({row['id'] for row in rows})!=len(rows): raise ValueError('duplicate_input_id') config_path = args.model/'byte_architecture.json' config = {} if config_path.exists(): config = json.loads(config_path.read_text()) model = CompactByteExtractor(width=config['width'],depth=config['attention_layers']) else: model = CompactByteExtractor() model.to(args.device).eval() weights = load_file(args.model/'byte_extractor.safetensors') if config.get('weights_format')=='int8': weights = decode_int8_weights(weights) model.load_state_dict(weights) classifier = ResourceTypeOutput(args.model) results = predict(model,rows,args.device,args.batch_size,classifier) args.output.parent.mkdir(parents=True,exist_ok=True) args.output.write_text(''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in results))
if __name__=='__main__': main()12345torch==2.10.0transformers==4.57.6safetensors==0.8.0sentencepiece==0.2.3protobuf==7.36.21234567891011121314151617181920212223242526272829303132333435363738{ "name": "joint_fields", "labels": [ "authored_book", "book_chapter", "conference_paper", "dataset", "edited_book", "journal_article", "proceedings", "report", "software", "thesis", "translated_book", "web" ], "width": 128, "context_width": 415, "field_outputs": 18, "field_weight": 0.4, "work_weight": 0.35, "cache_sha256": "6b4c4d3df309b0da81ae92e026b62c1efbdc96e7da6123f6acbedf9a7394b0e5", "raw_weight": 0.35, "biblatex_type_map": { "journal_article": "article", "authored_book": "book", "edited_book": "collection", "translated_book": "book", "book_chapter": "incollection", "proceedings": "proceedings", "conference_paper": "inproceedings", "thesis": "thesis", "report": "misc", "dataset": "misc", "software": "misc", "web": "online" }}123version https://git-lfs.github.com/spec/v1oid sha256:7054de1a8f6fa9dd88b06e46995bda2471a2e43933624c2aa1b4d1e464a9db46size 117544123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Classify a citation from its original characters with a bounded weight table."""
import mathimport jsonfrom pathlib import Path
import numpy as npfrom safetensors.torch import load_fileimport torchfrom torch import Tensor, nn
def character_features(text: str, ngrams: tuple[int, ...], buckets: int) -> np.ndarray: points = np.fromiter((ord(char) + 3 for char in text), dtype=np.uint32, count=len(text)) points = np.concatenate((np.array([1], dtype=np.uint32), points, np.array([2], dtype=np.uint32))) features = [] for n in ngrams: size = len(points) - n + 1 if size <= 0: continue hashes = np.full(size, n * 4099, dtype=np.uint32) for step in range(n): hashes = (hashes ^ points[step:step + size]) * np.uint32(16777619) hashes ^= hashes >> 16 features.append(hashes % buckets) return np.unique(np.concatenate(features)) if features else np.zeros(1, dtype=np.uint32)
def pack_features(rows: list[np.ndarray]) -> tuple[Tensor, Tensor, Tensor]: lengths = np.fromiter((len(row) for row in rows), dtype=np.int64, count=len(rows)) offsets = np.concatenate((np.zeros(1, dtype=np.int64), np.cumsum(lengths))) return (torch.from_numpy(np.concatenate(rows).astype(np.int64)), torch.from_numpy(offsets), torch.from_numpy(lengths.astype(np.float32)).rsqrt().unsqueeze(-1))
class ResourceTypeClassifier(nn.Module): def __init__(self, classes: int, buckets: int, width: int, context_width: int = 0) -> None: super().__init__() self.table = nn.EmbeddingBag(buckets, width, mode='sum', sparse=True, include_last_offset=True) nn.init.normal_(self.table.weight, std=1. / math.sqrt(width)) self.output = nn.Linear(width + context_width, classes)
def forward(self, packed: tuple[Tensor, Tensor, Tensor], context: Tensor | None = None) -> Tensor: indices, offsets, scale = packed summary = self.table(indices, offsets) * scale if context is not None: summary = torch.cat((summary, context), dim=-1) return self.output(summary)
def output_type(scores: Tensor, labels: list[str]) -> list[dict]: probabilities = scores.softmax(-1) confidence, indices = probabilities.max(-1) return [{'label': labels[index], 'confidence': float(value)} for index, value in zip(indices.tolist(), confidence.tolist(), strict=True)]
def pool_context(hidden: Tensor, lengths: Tensor, outer_logits: Tensor) -> Tensor: valid = torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None] mask = valid.unsqueeze(-1) mean = (hidden * mask).sum(1) / lengths[:, None] maximum = hidden.masked_fill(~mask, -torch.inf).amax(1) mass = (outer_logits.float().softmax(-1) * mask).sum(1).log1p() return torch.cat((mean, maximum, mass), dim=-1).float()
class ContextResourceClassifier(nn.Module): def __init__(self, classes: int, inputs: int, width: int, fields: int) -> None: super().__init__() self.register_buffer('center', torch.zeros(inputs)) self.register_buffer('spread', torch.ones(inputs)) self.features = nn.Sequential(nn.Linear(inputs, width), nn.GELU(), nn.Dropout(.15)) self.kind = nn.Linear(width, classes) self.fields = nn.Linear(width, fields) if fields else None self.kind_from_fields = nn.Linear(fields, classes, bias=False) if fields else None self.fields_from_kind = nn.Linear(classes, fields, bias=False) if fields else None
def forward(self, context: Tensor) -> tuple[Tensor, Tensor | None]: hidden = self.features(((context - self.center) / self.spread).clamp(-12., 12.)) kind = self.kind(hidden) if self.fields is None: return kind, None fields = self.fields(hidden) kind = kind + self.kind_from_fields(fields.sigmoid()) return kind, fields + self.fields_from_kind(kind.softmax(-1))
class ResourceTypeOutput: def __init__(self, folder: Path) -> None: spec = json.loads((folder / 'resource_type.json').read_text()) self.labels = spec['labels'] self.biblatex_type_map = spec['biblatex_type_map'] self.temperature = spec.get('temperature', 1.) self.threshold = spec.get('abstention_threshold', 0.) self.field_scale = spec.get('field_scale', 0.) self.raw_weight = spec.get('raw_weight', 0.) if spec.get('context_width'): self.uses_context = True self.model = ContextResourceClassifier(len(self.labels), spec['context_width'], spec['width'], spec.get('field_outputs', 0)) else: self.uses_context = False self.model = ResourceTypeClassifier(len(self.labels), spec['buckets'], spec['width']) self.ngrams, self.buckets = tuple(spec['ngrams']), spec['buckets'] self.model.load_state_dict(load_file(folder / 'resource_type.safetensors')) self.model.eval() if self.raw_weight: raw = json.loads((folder / 'resource_type_raw.json').read_text()) if raw['labels'] != self.labels or not self.uses_context: raise ValueError('resource_type_ensemble_labels_changed') self.raw_model = ResourceTypeClassifier(len(self.labels), raw['buckets'], raw['width']) self.raw_model.load_state_dict(load_file(folder / 'resource_type_raw.safetensors')) self.raw_model.eval() self.raw_ngrams, self.raw_buckets = tuple(raw['ngrams']), raw['buckets'] if self.field_scale and not spec.get('field_outputs'): raise ValueError('resource_type_field_scores_missing')
@torch.inference_mode() def field_evidence(self, context: Tensor, labels: int) -> Tensor: fields = self.model(context.half().float().cpu())[1] return fields[:, :labels].tanh().to(context.device) * self.field_scale
@torch.inference_mode() def attach(self, inputs: list[dict], predictions: list[dict], context: Tensor | None = None) -> list[dict]: if self.uses_context: if context is None or len(context) != len(inputs): raise ValueError('resource_type_context_missing') scores = self.model(context.half().float().cpu())[0] if self.raw_weight: raw_rows = [character_features(row['text'], self.raw_ngrams, self.raw_buckets) for row in inputs] scores = scores.lerp(self.raw_model(pack_features(raw_rows)), self.raw_weight) else: rows = [character_features(row['text'], self.ngrams, self.buckets) for row in inputs] scores = self.model(pack_features(rows)) typed = {} scaled = scores / self.temperature probabilities = scaled.softmax(-1).tolist() for row, kind, values in zip(inputs, output_type(scaled, self.labels), probabilities, strict=True): totals = {} for label, score in zip(self.labels, values, strict=True): mapped = self.biblatex_type_map[label] totals[mapped] = totals.get(mapped, 0.) + score ranked = sorted(totals.items(), key=lambda pair: (-pair[1], pair[0])) top_label, top_score = ranked[0] kind['biblatex'] = { 'selected': top_label if top_score >= .90 else None, 'candidates': [{'type': label, 'score': score} for label, score in ranked], } if kind['confidence'] < self.threshold: kind['label'] = None typed[row['id']] = kind if typed.keys() != {row['id'] for row in predictions}: raise ValueError('resource_type_predictions_misaligned') return [{**row, 'resource_type': typed[row['id']]} for row in predictions]
class TypeFieldCountEvidence(nn.Module): def __init__(self, classifier: ResourceTypeOutput, fields: int) -> None: super().__init__() self.classifier = classifier self.fields = fields
def forward(self, hidden: Tensor, outer: Tensor, lengths: Tensor) -> Tensor: bias = self.classifier.field_evidence(pool_context(hidden, lengths, outer), self.fields) zero_counts = torch.zeros_like(bias).unsqueeze(-1) return torch.cat((zero_counts, bias.unsqueeze(-1).expand(-1, -1, 3)), dim=-1)123456789101112131415161718192021222324252627{ "labels": [ "authored_book", "book_chapter", "conference_paper", "dataset", "edited_book", "journal_article", "proceedings", "report", "software", "thesis", "translated_book", "web" ], "ngrams": [ 2, 3, 4, 5 ], "buckets": 32768, "width": 12, "work_weight": 0.0, "class_weight": 0.0, "learning_rate": 0.12}123version https://git-lfs.github.com/spec/v1oid sha256:0b49fd0accea70d1138473da425a326311d9cd9574fceb97da21df42f62f43e5size 7869681"""分析スクリプトで共有するモジュール。"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""bibformDatasetTrialの役割付き文字範囲と、原文だけを使う評価契約。"""from collections import Counter, defaultdictfrom copy import deepcopyimport hashlibimport jsonimport reimport random
from shared.csl_spans import canonical_annotationsfrom shared.dataset_schema import FIELD_MAP, visible_valuefrom shared.text_offsets import transform_characters
NAME = 'bibformDatasetTrial'FIELDS = ('TITLE', 'CONTAINER_TITLE', 'DATE', 'VOLUME', 'ISSUE', 'PAGES', 'ISSUER', 'DOI', 'ISBN', 'URL', 'EDITION', 'VERSION')ROLES = ('author.work', 'editor.work', 'translator.work', 'author.container', 'editor.container', 'translator.container')
def validate(text: str, target: dict) -> None: if set(target) != {'id', 'fields', 'contributors'}: raise ValueError('invalid_trial_target_keys') previous = 0 for field in target['fields']: if field['label'] not in FIELDS or not previous <= field['start'] < field['end'] <= len(text): raise ValueError('invalid_trial_field') previous = field['end'] if field['value'] != visible_value(text[field['start']:field['end']], field['label']): raise ValueError('trial_field_not_grounded') previous = 0 for person in target['contributors']: if set(person) != {'kind', 'start', 'end', 'value', 'name_parts', 'roles'}: raise ValueError('invalid_trial_contributor_keys') a, b = person['start'], person['end'] if person['kind'] not in ('person', 'organization') or not previous <= a < b <= len(text): raise ValueError('invalid_trial_contributor') previous = b if person['value'] != visible_value(text[a:b], 'CONTRIBUTOR'): raise ValueError('trial_contributor_not_grounded') if not person['roles'] or person['roles'] != sorted(set(person['roles'])) or set(person['roles']) - set(ROLES): raise ValueError('invalid_trial_roles') parts = [] for part, span in person['name_parts'].items(): if part not in ('family', 'given') or not a <= span['start'] < span['end'] <= b: raise ValueError('invalid_trial_name_part') if span['value'] != visible_value(text[span['start']:span['end']], part): raise ValueError('trial_name_not_grounded') parts.append((span['start'], span['end'])) if len(parts) == 2 and max(parts[0][0], parts[1][0]) < min(parts[0][1], parts[1][1]): raise ValueError('trial_name_parts_overlap') if person['kind'] == 'organization' and parts: raise ValueError('organization_with_person_parts') if any(f['start'] < b and f['end'] > a for f in target['fields']): raise ValueError('trial_contributor_field_overlap')
def from_rendered(identifier: str, html: str, plain_html: str) -> tuple[str, dict, list[dict]]: text, annotations = canonical_annotations(html, plain_html) fields, contributors, trace = [], [], [] for label, start, end in annotations: if label.startswith(('TRIAL_PERSON:', 'TRIAL_ORGANIZATION:')): kind, source, roles = label.removeprefix('TRIAL_').split(':') person = {'kind': kind.lower(), 'start': start, 'end': end, 'value': visible_value(text[start:end], 'CONTRIBUTOR'), 'name_parts': {}, 'roles': sorted(roles.split('+'))} for part, left, right in annotations: if part in ('FAMILY', 'GIVEN') and start <= left < right <= end: if part.lower() in person['name_parts']: raise ValueError('fragmented_trial_name') person['name_parts'][part.lower()] = {'start': left, 'end': right, 'value': visible_value(text[left:right], part)} contributors.append(person) trace.append({'source_person_index': int(source), 'start': start, 'end': end, 'roles': person['roles']}) elif label in FIELD_MAP and FIELD_MAP[label] in FIELDS: fields.append({'label': FIELD_MAP[label], 'start': start, 'end': end, 'value': visible_value(text[start:end], FIELD_MAP[label])}) fields.sort(key=lambda f: (f['start'], -f['end'])) unique = [] for field in fields: if unique and field['start'] < unique[-1]['end']: if field == unique[-1]: continue raise ValueError('overlapping_trial_fields') unique.append(field) contributors.sort(key=lambda p: (p['start'], p['end'])) target = {'id': identifier, 'fields': unique, 'contributors': contributors} validate(text, target) if not any(f['label'] == 'TITLE' for f in unique) or not contributors: raise ValueError('trial_missing_title_or_responsibility') return text, target, trace
def signature(row: dict, *, include_roles: bool = True) -> tuple: fields = tuple(sorted((f['label'], f['start'], f['end']) for f in row['fields'])) people = tuple(sorted((p['kind'], p['start'], p['end'], tuple(sorted((k, s['start'], s['end']) for k, s in p['name_parts'].items())), tuple(p.get('roles', [])) if include_roles else ()) for p in row['contributors'])) return fields, people
def formatting_noise(text: str, target: dict, seed: int, identifier: str) -> tuple[str, dict]: rng = random.Random(seed) punctuation = {',': ',', ';': ';', ':': ':', '(': '(', ')': ')', '[': '[', ']': ']'} replacements = [] for char in text: if char == ' ' and rng.random() < .12: replacements.append('\n' if rng.random() < .5 else ' ') elif char in punctuation and rng.random() < .4: replacements.append(punctuation[char]) elif char in ('–', '—') and rng.random() < .5: replacements.append('-') else: replacements.append(char) result = deepcopy(target); result['id'] = identifier annotations, objects = [], [] for field in result['fields']: annotations.append((str(len(objects)), field['start'], field['end'])); objects.append((field, field['label'])) for person in result['contributors']: annotations.append((str(len(objects)), person['start'], person['end'])); objects.append((person, 'CONTRIBUTOR')) for part, span in person['name_parts'].items(): annotations.append((str(len(objects)), span['start'], span['end'])); objects.append((span, part)) text, transformed = transform_characters(text, annotations, replacements) if len(transformed) != len(objects): raise ValueError('noise_removed_annotated_content') for key, start, end in transformed: obj, label = objects[int(key)] obj.update(start=start, end=end, value=visible_value(text[start:end], label)) validate(text, result) return text, result
def trim_whitespace_boundaries(text: str, prediction: dict) -> dict: """範囲注釈の規約に合わせ、原文の空白を範囲の両端から除く。""" result = deepcopy(prediction)
def trim(span: dict) -> bool: while span['start'] < span['end'] and text[span['start']].isspace(): span['start'] += 1 while span['end'] > span['start'] and text[span['end']-1].isspace(): span['end'] -= 1 return span['start'] < span['end']
result['fields'] = [field for field in result['fields'] if trim(field)] people = [] for person in result['contributors']: if trim(person): person['name_parts'] = {key: span for key, span in person['name_parts'].items() if trim(span)} people.append(person) result['contributors'] = people validate(text, result) return result
BRACKET_GROUPS = (('((', '))'), ('[[', ']]'), ('{{', '}}'), ('「', '」'), ('『', '』'), ('【', '】'), ('〔', '〕'), ('〈', '〉'), ('《', '》'))
def unmatched_terminal_closer(text: str, field: dict) -> str | None: value=text[field['start']:field['end']] if not value:return None for opening,closing in BRACKET_GROUPS: if value[-1] in closing and sum(value.count(c) for c in closing)>sum(value.count(c) for c in opening): return closing[-1] return None
def trim_unmatched_closing_boundaries(text: str, prediction: dict, allowed_pairs: list[list[str]]) -> dict: """訓練正解で許された項目だけ、対応する開き括弧のない末尾を範囲から外す。""" result=deepcopy(prediction);allowed={tuple(p) for p in allowed_pairs};fields=[] for field in result['fields']: while (closer:=unmatched_terminal_closer(text,field)) and (field['label'],closer) in allowed: field['end']-=1 while field['end']>field['start'] and text[field['end']-1].isspace():field['end']-=1 if field['end']>field['start']: field['value']=visible_value(text[field['start']:field['end']],field['label']);fields.append(field) result['fields']=fields;validate(text,result);return result
def align_work_alias_roles(prediction: dict, blocked_transfers: list[list[str]] | None = None) -> dict: """引用内の一意なフルネームに対応する姓の略記で、対象資料内の役割をそろえる。""" result = deepcopy(prediction) blocked = {tuple(pair) for pair in blocked_transfers or []} full = defaultdict(set) for person in result['contributors']: parts = person['name_parts'] if person['kind'] == 'person' and set(parts) == {'family', 'given'}: full[parts['family']['value']].add((parts['given']['value'], tuple(person['roles']))) for person in result['contributors']: parts, roles = person['name_parts'], person['roles'] if person['kind'] != 'person' or set(parts) != {'family'} or len(roles) != 1 or not roles[0].endswith('.work'): continue candidates = full.get(parts['family']['value'], set()) if len(candidates) == 1: _, candidate_roles = next(iter(candidates)) if (len(candidate_roles) == 1 and candidate_roles[0].endswith('.work') and (roles[0], candidate_roles[0]) not in blocked): person['roles'] = list(candidate_roles) return result
def evaluate(targets: list[dict], predictions: dict, metadata: dict) -> dict: groups, conditions = defaultdict(list), defaultdict(list) exact = structural = role_correct = role_total = 0 for target in targets: prediction = predictions.get(target['id'], {'id': target['id'], 'fields': [], 'contributors': []}) hit = signature(target) == signature(prediction) exact += hit structural += signature(target, include_roles=False) == signature(prediction, include_roles=False) row = metadata[target['id']] groups[row['group_id']].append(int(hit)); conditions[row['condition']].append(int(hit)) predicted = {(p['kind'], p['start'], p['end']): p for p in prediction['contributors']} for p in target['contributors']: role_total += 1 other = predicted.get((p['kind'], p['start'], p['end'])) role_correct += bool(other and other.get('roles') == p['roles']) count = len(targets) return {'records': count, 'reference_exact': exact, 'reference_exact_rate': exact / max(count, 1), 'primary_group_macro_exact': sum(sum(v)/len(v) for v in groups.values())/max(len(groups), 1), 'work_groups': len(groups), 'without_roles_reference_exact_rate': structural/max(count, 1), 'contributor_with_roles_correct': role_correct, 'gold_contributors': role_total, 'contributor_with_roles_recall': role_correct/max(role_total, 1), 'by_condition': {k: {'records': len(v), 'exact': sum(v), 'accuracy': sum(v)/len(v)} for k, v in sorted(conditions.items())}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""既存の重みを保存したまま、選んだ線形層へ小さな学習可能な差分を加える。"""from pathlib import Path
from safetensors.torch import load_fileimport torchfrom torch import nn
class AdapterLinear(nn.Module): def __init__(self, base: nn.Linear, rank: int, alpha: float) -> None: super().__init__() self.base = base self.in_features, self.out_features = base.in_features, base.out_features self.down = nn.Linear(base.in_features, rank, bias=False) self.up = nn.Linear(rank, base.out_features, bias=False) self.scale = alpha/rank nn.init.zeros_(self.up.weight) self.to(device=base.weight.device, dtype=base.weight.dtype)
@property def weight(self): return self.base.weight
@property def bias(self): return self.base.bias
def forward(self, features): return self.base(features)+self.up(self.down(features))*self.scale
def install_adapters(member: nn.Module, configuration: dict) -> dict: member.requires_grad_(False) config = dict(configuration) layers = member.encoder.encoder.layer if 'targets' not in config: selected = list(range(len(layers)-config['last_layers'], len(layers))) if not selected or min(selected) < 0: raise ValueError('invalid_adapter_layer_count') suffixes = ('attention.self.query', 'attention.self.key', 'attention.self.value', 'attention.output.dense', 'intermediate.dense', 'output.dense') config['targets'] = [f'encoder.encoder.layer.{index}.{suffix}' for index in selected for suffix in suffixes] config['targets'].append('projection') if member.global_projection is not None: config['targets'].append('global_projection') config['normalizations'] = [f'encoder.encoder.layer.{index}.{name}' for index in selected for name, module in layers[index].named_modules() if isinstance(module, nn.LayerNorm)] for name in config['targets']: base = member.get_submodule(name) if not isinstance(base, nn.Linear): raise ValueError(f'adapter_target_not_linear:{name}') parent, _, key = name.rpartition('.') rank = config.get('target_ranks', {}).get(name, config['rank']) alpha = config.get('target_alphas', {}).get(name, config['alpha']) if rank < 1 or alpha <= 0: raise ValueError('invalid_adapter_rank_or_scale') wrapper = AdapterLinear(base, rank, alpha) setattr(member.get_submodule(parent) if parent else member, key, wrapper) if base.bias is not None and config.get('train_biases', True): base.bias.requires_grad_(True) for name in config['normalizations']: module = member.get_submodule(name) if not isinstance(module, nn.LayerNorm): raise ValueError('adapter_normalization_mismatch') if config.get('train_normalizations', True): module.requires_grad_(True) names = sorted(name for name, parameter in member.named_parameters() if parameter.requires_grad) if 'trainable_parameters' in config: assert names == config['trainable_parameters'] config['trainable_parameters'] = names config['trainable_parameter_count'] = sum(parameter.numel() for parameter in member.parameters() if parameter.requires_grad) return config
def trainable_state(member: nn.Module, configuration: dict, half: bool = False) -> dict: parameters = dict(member.named_parameters()) return {name: (parameters[name].detach().cpu().half() if half else parameters[name].detach().cpu()).contiguous() for name in configuration['trainable_parameters']}
def load_adapter_state(member: nn.Module, configuration: dict, source: Path | dict) -> None: state = load_file(source) if isinstance(source, Path) else source assert set(state) == set(configuration['trainable_parameters']) missing, unexpected = member.load_state_dict(state, strict=False) assert not unexpected and not set(missing) & set(configuration['trainable_parameters'])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750"""原文の固定文字表現から、書誌範囲・姓名・人物ごとの複数役割を予測する。"""from pathlib import Pathimport json
import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom safetensors.torch import load_file
from shared.bibform_trial import FIELDS, ROLES, validatefrom shared.dataset_schema import bio_labelsfrom shared.span_tagger import EncodedCitation, OUTER_NAMES, NAME_NAMES, load_packagefrom shared.inference_strategies import structural_predictionsfrom shared.range_extraction import RANGE_TYPES, prediction_from_rangesfrom shared.range_extraction import position_features
def utf8_character_ids(text: str) -> np.ndarray: values = np.frombuffer(text.encode('utf-8'), dtype=np.uint8) first = (values & 0xc0) != 0x80 offsets = np.arange(len(values)) starts = np.maximum.accumulate(np.where(first, offsets, 0)) result = np.zeros((len(text), 4), dtype=np.int64) result[first.cumsum()-1, offsets-starts] = values.astype(np.int64)+1 return result
class RawCharacterEncoder(nn.Module): def __init__(self, output_width: int = 192, dilations: tuple[int, ...] = (1,1)) -> None: super().__init__() self.bytes = nn.Embedding(257, 16, padding_idx=0) self.convolutions = nn.ModuleList(nn.Conv1d(64,64,5,padding=2*d,dilation=d) for d in dilations) self.norms = nn.ModuleList(nn.LayerNorm(64) for _ in self.convolutions) self.projection = nn.Linear(64, output_width) nn.init.zeros_(self.projection.weight); nn.init.zeros_(self.projection.bias)
def forward(self, values, lengths): hidden = self.bytes(values).flatten(-2) mask = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None] for convolution, norm in zip(self.convolutions, self.norms): hidden = norm(hidden+F.gelu(convolution(hidden.transpose(1, 2)).transpose(1, 2)))*mask return self.projection(hidden)
class CitationAttention(nn.Module): def __init__(self, width: int = 192) -> None: super().__init__() self.norm_attention = nn.LayerNorm(width) self.attention = nn.MultiheadAttention(width, 6, dropout=.1, batch_first=True) self.norm_output = nn.LayerNorm(width) self.feedforward = nn.Sequential(nn.Linear(width, 2*width), nn.GELU(), nn.Dropout(.1), nn.Linear(2*width, width)) nn.init.zeros_(self.attention.out_proj.weight); nn.init.zeros_(self.attention.out_proj.bias) nn.init.zeros_(self.feedforward[-1].weight); nn.init.zeros_(self.feedforward[-1].bias)
def forward(self, hidden, positions, mask): values = self.norm_attention(hidden)+.1*positions context = self.attention(values, values, values, key_padding_mask=mask, need_weights=False)[0] hidden = hidden+F.dropout(context, .1, self.training) return hidden+F.dropout(self.feedforward(self.norm_output(hidden)), .1, self.training)
class RoleGlobalContext(nn.Module): def __init__(self, width: int = 192) -> None: super().__init__() self.query = nn.Sequential(nn.LayerNorm(5*width), nn.Linear(5*width, width)) self.keys = nn.LayerNorm(width) self.position = nn.Linear(1, width) self.attention = nn.MultiheadAttention(width, 6, dropout=.1, batch_first=True) self.output = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, 5*width)) nn.init.zeros_(self.output[-1].weight) nn.init.zeros_(self.output[-1].bias)
def forward(self, hidden, lengths, batch, values): positions = torch.arange(hidden.shape[1], device=hidden.device, dtype=hidden.dtype) positions = positions[None, :, None]/lengths[:, None, None].clamp_min(1) keys = self.keys(hidden)+self.position(positions) mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None] context = self.attention(self.query(values)[:, None], keys[batch], keys[batch], key_padding_mask=mask[batch], need_weights=False)[0][:, 0] return self.output(context)
class RoleSummaryContext(nn.Module): def __init__(self, width: int = 192) -> None: super().__init__() self.network = nn.Sequential(nn.LayerNorm(7*width+6), nn.Linear(7*width+6, 64), nn.GELU(), nn.Dropout(.1), nn.Linear(64, 5*width)) nn.init.zeros_(self.network[-1].weight); nn.init.zeros_(self.network[-1].bias)
def forward(self, hidden, lengths, batch, start, end, values): valid = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None] mean = (hidden*valid).sum(1)/lengths[:, None] maximum = hidden.masked_fill(~valid, -torch.inf).amax(1) counts = torch.bincount(batch, minlength=len(lengths)) offsets = counts.cumsum(0)-counts rank = torch.arange(len(batch), device=hidden.device)-torch.repeat_interleave(offsets, counts) size = lengths[batch].float(); number = counts[batch].float() positions = torch.stack([start/size, end/size, (end-start)/size, rank/(number-1).clamp_min(1), number/(number+1), 1/size], -1) features = torch.cat([values, mean[batch], maximum[batch], positions], -1) return self.network(features)
def structural_loss_mean(losses, weights, mode, hard_fraction=.25): weighted = losses*weights if mode == 'token_mean': return weighted.sum()/weights.sum().clamp_min(1) if mode == 'reference_mean' or hard_fraction == 1: return (weighted.sum(1)/weights.sum(1).clamp_min(1)).mean() if mode != 'reference_hard' or not 0 < hard_fraction <= 1: raise ValueError('invalid_structural_loss') order = weighted.masked_fill(weights <= 0, -torch.inf).argsort(1, descending=True) counts = ((weights > 0).sum(1)*hard_fraction).ceil().long() selected = torch.arange(losses.shape[1], device=losses.device)[None, :] < counts[:, None] numerator = (weighted.gather(1, order)*selected).sum(1) denominator = (weights.gather(1, order)*selected).sum(1).clamp_min(1) return (numerator/denominator).mean()
class TrialBIO(nn.Module): def __init__(self, width: int = 768, role_weight: float = 1.0, context: int = 32, sequence: str = 'none', semantic_width: int = 0, boundary_weight: float = 1., role_decoder: str = 'independent', structure: str = 'single_title', raw_characters: bool = False, label_transitions: bool = False, transition_scale: float = 0., raw_semantic_width: int = 0, attention_layers: int = 0, role_global_context: bool = False, structural_loss: str = 'token_mean', hard_token_fraction: float = .25, global_presence: bool = False, global_presence_weight: float = .1, hidden_width: int = 192, role_hidden_width: int = 128, role_summary_context: bool = False, raw_context_residual: bool = False, additional_attention_layers: int = 0, additional_attention_scale: float = 1.) -> None: super().__init__() if hidden_width < 6 or hidden_width % 6 or role_hidden_width < 1: raise ValueError('invalid_head_width') self.hidden_width = hidden_width; self.role_hidden_width = role_hidden_width self.features = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, hidden_width), nn.GELU()) self.outer = nn.Linear(hidden_width, 31); self.names = nn.Linear(hidden_width, 5) 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))) self.role_global_context = role_global_context if role_global_context: self.role_global = RoleGlobalContext(hidden_width) self.role_summary_context = role_summary_context if role_summary_context: self.role_summary = RoleSummaryContext(hidden_width) self.global_presence = global_presence self.field_presence_prior = None self.global_presence_weight = global_presence_weight if global_presence: self.global_presence_head = nn.Sequential(nn.LayerNorm(2*hidden_width), nn.Linear(2*hidden_width, 128), nn.GELU(), nn.Linear(128, len(FIELDS)+len(ROLES))) self.global_presence_projection = nn.Linear(len(FIELDS)+len(ROLES), hidden_width) nn.init.zeros_(self.global_presence_projection.weight) nn.init.zeros_(self.global_presence_projection.bias) self.register_buffer('presence_positive_weights', torch.ones(len(FIELDS)+len(ROLES))) self.role_weight = role_weight; self.context = context if structural_loss not in ('token_mean', 'reference_mean', 'reference_hard', 'contributors_only', 'joint_crf', 'joint_crf_boundary') or not 0 < hard_token_fraction <= 1: raise ValueError('invalid_structural_loss') if structural_loss.startswith('joint_crf') and (structure != 'unrestricted' or not label_transitions): raise ValueError('joint_sequence_loss_requires_the_joint_transition_decoder') self.structural_loss = structural_loss; self.hard_token_fraction = hard_token_fraction self.register_buffer('role_positive_weights', torch.ones(len(ROLES))) self.base_width = width; self.semantic_width = semantic_width self.raw_semantic_width = raw_semantic_width if raw_semantic_width: self.raw_semantic_features = nn.Sequential(nn.LayerNorm(raw_semantic_width), nn.Linear(raw_semantic_width, hidden_width)) nn.init.zeros_(self.raw_semantic_features[-1].weight) nn.init.zeros_(self.raw_semantic_features[-1].bias) self.boundary_weight = boundary_weight if structure not in ('single_title', 'unrestricted'): raise ValueError('unsupported_structure') self.structure = structure self.label_transitions = label_transitions self.transition_scale = transition_scale if label_transitions: if structure != 'unrestricted': raise ValueError('learned_label_transitions_require_unrestricted_structure') for layer, size in (('outer', 31), ('names', 5)): self.register_buffer(f'{layer}_transitions', torch.zeros(size, size)) self.register_buffer(f'{layer}_start', torch.zeros(size)) self.register_buffer(f'{layer}_end', torch.zeros(size)) self.raw_characters = raw_characters if raw_characters: self.raw_encoder = RawCharacterEncoder(hidden_width) self.raw_context = None if raw_context_residual: self.install_raw_context() if role_decoder not in ('independent', 'powerset'): raise ValueError('unsupported_role_decoder') self.role_decoder = role_decoder if role_decoder == 'powerset': masks = ((torch.arange(1, 2**len(ROLES))[:, None] >> torch.arange(len(ROLES))[None, :]) & 1).float() self.register_buffer('role_masks', masks, persistent=False) self.register_buffer('role_class_weights', torch.ones(len(masks))) self.role_combo_bias = nn.Parameter(torch.zeros(len(masks))) if semantic_width: self.semantic_features = nn.Sequential(nn.LayerNorm(semantic_width), nn.Linear(semantic_width, hidden_width)) nn.init.zeros_(self.semantic_features[-1].weight); nn.init.zeros_(self.semantic_features[-1].bias) if sequence not in ('none', 'bilstm', 'transformer'): raise ValueError('unsupported_sequence_context') self.sequence_kind = sequence if sequence == 'bilstm': self.sequence = nn.LSTM(hidden_width, hidden_width//2, batch_first=True, bidirectional=True) self.sequence_projection = nn.Linear(hidden_width, hidden_width) nn.init.zeros_(self.sequence_projection.weight); nn.init.zeros_(self.sequence_projection.bias) elif sequence == 'transformer': self.sequence = nn.ModuleList([CitationAttention(hidden_width) for _ in range(3)]) self.global_attention = nn.ModuleList([CitationAttention(hidden_width) for _ in range(attention_layers)]) self.additional_attention = nn.ModuleList([CitationAttention(hidden_width) for _ in range(additional_attention_layers)]) self.additional_attention_scale = additional_attention_scale
def warm_start(self, path: Path) -> None: missing, unexpected = self.load_state_dict(load_file(path), strict=False) assert not unexpected assert all(k.startswith(('role_head.', 'role_global.', 'role_summary.', 'sequence.', 'sequence_projection.', 'semantic_features.', 'raw_encoder.')) or k in ('role_positive_weights', 'role_class_weights', 'role_combo_bias') for k in missing)
def install_raw_context(self) -> None: if not self.raw_characters: raise ValueError('raw_context_requires_original_character_features') self.raw_context = RawCharacterEncoder(self.hidden_width,(1,2,4,8,16))
def encode(self, features, lengths, inputs=None, return_presence=False): hidden = self.features(features[..., :self.base_width]) if self.semantic_width: hidden = hidden+self.semantic_features(features[..., self.base_width:self.base_width+self.semantic_width]) if self.raw_semantic_width: hidden = hidden+self.raw_semantic_features(features[..., self.base_width+self.semantic_width:]) if self.raw_characters: if inputs is None: raise ValueError('raw_character_encoder_requires_original_text') byte_ids = np.zeros((len(inputs), features.shape[1], 4), dtype=np.int64) for i, row in enumerate(inputs): byte_ids[i, :len(row['text'])] = utf8_character_ids(row['text']) byte_ids = torch.from_numpy(byte_ids).to(features.device) hidden = hidden+self.raw_encoder(byte_ids,lengths) if self.raw_context is not None: hidden = hidden+self.raw_context(byte_ids,lengths) if self.sequence_kind == 'bilstm': packed = nn.utils.rnn.pack_padded_sequence(hidden, lengths.cpu(), batch_first=True, enforce_sorted=False) contextual, _ = self.sequence(packed) contextual, _ = nn.utils.rnn.pad_packed_sequence(contextual, batch_first=True, total_length=hidden.shape[1]) hidden = hidden+self.sequence_projection(F.dropout(contextual, .1, self.training)) elif self.sequence_kind == 'transformer': positions = position_features(hidden.shape[1], self.hidden_width, hidden.device)[None, :, :] mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None] for layer in self.sequence: hidden = layer(hidden, positions, mask) if self.global_attention or self.additional_attention: positions = position_features(hidden.shape[1], self.hidden_width, hidden.device)[None, :, :] mask = torch.arange(hidden.shape[1], device=hidden.device)[None, :] >= lengths[:, None] for layer in self.global_attention: hidden = layer(hidden, positions, mask) if self.additional_attention and self.additional_attention_scale: updated = hidden for layer in self.additional_attention: updated = layer(updated, positions, mask) hidden = hidden.lerp(updated, self.additional_attention_scale) presence = None if self.global_presence: valid = (torch.arange(hidden.shape[1], device=hidden.device)[None, :] < lengths[:, None])[..., None] mean = (hidden*valid).sum(1)/lengths[:, None] maximum = hidden.masked_fill(~valid, -torch.inf).amax(1) presence = self.global_presence_head(torch.cat([mean, maximum], -1)) hidden = hidden+self.global_presence_projection(presence.sigmoid())[:, None] return (hidden, presence) if return_presence else hidden
def role_scores(self, hidden, lengths, mentions): if not mentions: return hidden.new_zeros((0, len(ROLES))) device = hidden.device batch = torch.tensor([m[0] for m in mentions], device=device) start = torch.tensor([m[1] for m in mentions], device=device) end = torch.tensor([m[2] for m in mentions], device=device) prefix = F.pad(hidden.cumsum(1), (0, 0, 1, 0)) def mean(left, right): return (prefix[batch, right]-prefix[batch, left])/(right-left).clamp_min(1)[:, None] left = (start-self.context).clamp_min(0) right = torch.minimum(end+self.context, lengths[batch]) values = torch.cat([hidden[batch, start], hidden[batch, end-1], mean(start, end), mean(left, start), mean(end, right)], -1) if self.role_global_context: values = values+self.role_global(hidden, lengths, batch, values) if self.role_summary_context: values = values+self.role_summary(hidden, lengths, batch, start, end, values) return self.role_head(values)
def loss(self, features, lengths, targets, inputs=None, consistency_groups=None, consistency_weight=0., return_supervision=False): if self.global_presence: hidden, presence = self.encode(features, lengths, inputs, return_presence=True) presence_gold = np.zeros((len(targets), len(FIELDS)+len(ROLES)), dtype=np.float32) else: hidden = self.encode(features, lengths, inputs) gold_values = np.full((len(targets), 2, features.shape[1]), -100, dtype=np.int64) mentions, role_gold = [], [] for i, (target, length) in enumerate(zip(targets, lengths.tolist(), strict=True)): if self.global_presence: for field in target['fields']: presence_gold[i, FIELDS.index(field['label'])] = 1 for person in target['contributors']: for role in person['roles']: presence_gold[i, len(FIELDS)+ROLES.index(role)] = 1 outer = [(f['label'], f['start'], f['end']) for f in target['fields']] outer += [(p['kind'], p['start'], p['end']) for p in target['contributors']] names = [(key, part['start'], part['end']) for p in target['contributors'] for key, part in p['name_parts'].items()] gold_values[i, 0, :length] = bio_labels(length, outer, OUTER_NAMES) gold_values[i, 1, :length] = bio_labels(length, names, NAME_NAMES) for person in target['contributors']: mentions.append((i, person['start'], person['end'])) role_gold.append([float(role in person['roles']) for role in ROLES]) gold = torch.from_numpy(gold_values).to(features.device) structural = hidden.sum()*0 outer_logits, name_logits = self.outer(hidden), self.names(hidden) joint = self.structural_loss.startswith('joint_crf') if joint: from shared.joint_sequence_loss import joint_sequence_loss structural = joint_sequence_loss(outer_logits, name_logits, gold_values, lengths, self.outer_transitions, self.names_transitions, self.outer_start, self.names_start, self.outer_end, self.names_end, self.transition_scale) if not joint or self.structural_loss == 'joint_crf_boundary': mode = 'token_mean' if joint else self.structural_loss outer_tags = gold[:, 0] if mode == 'contributors_only': first = 1 + 2 * OUTER_NAMES.index('person') non_contributors = outer_logits[..., :first].float().logsumexp(-1, keepdim=True) outer_logits = torch.cat((non_contributors, outer_logits[..., first:]), dim=-1) outer_tags = torch.where(outer_tags >= first, outer_tags - first + 1, outer_tags.clamp(max=0)) mode = 'reference_mean' for logits, tags in ((outer_logits, outer_tags), (name_logits, gold[:, 1])): losses = F.cross_entropy(logits.transpose(1, 2), tags, reduction='none') valid = tags >= 0 classes = (tags+1)//2 next_classes = F.pad(classes[:, 1:], (0, 1), value=-1) boundary = ((tags % 2 == 1) | (classes != next_classes)) & (tags > 0) weights = valid.float()*(1+(self.boundary_weight-1)*boundary) value = structural_loss_mean(losses, weights, mode, self.hard_token_fraction) structural = structural+(.1*value if joint else value) if mentions: score = self.role_scores(hidden, lengths, mentions) labels = torch.tensor(role_gold, device=features.device) if self.role_decoder == 'powerset': codes = (labels.long()*(1 << torch.arange(len(ROLES), device=features.device))).sum(-1)-1 roles = F.cross_entropy(score@self.role_masks.T+self.role_combo_bias, codes, weight=self.role_class_weights) else: roles = F.binary_cross_entropy_with_logits(score, labels, pos_weight=self.role_positive_weights) else: roles = hidden.sum()*0 labels = hidden.new_empty((0,len(ROLES))) total = structural+self.role_weight*roles if self.global_presence: total = total+self.global_presence_weight*F.binary_cross_entropy_with_logits( presence, torch.from_numpy(presence_gold).to(features.device), pos_weight=self.presence_positive_weights) if not consistency_weight or consistency_groups is None: return (total,gold,labels) if return_supervision else total consistency = hidden.sum()*0 if consistency_groups is not None: if len(consistency_groups) != len(targets): raise ValueError('invalid_training_consistency_groups') groups, views, spans, group_per_view = {}, {}, [], [] for batch, (target, group) in enumerate(zip(targets, consistency_groups, strict=True)): annotated = [(('field', field['label']), field['start'], field['end']) for field in target['fields']] annotated += [(('role', person['kind'], tuple(person['roles'])), person['start'], person['end']) for person in target['contributors']] for label, start, end in annotated: key = (group, label) group_id = groups.setdefault(key, len(groups)) if (group_id, batch) not in views: views[group_id, batch] = len(views); group_per_view.append(group_id) spans.append((batch, start, end, views[group_id, batch])) counts = np.bincount(group_per_view) if spans else np.zeros(0, dtype=np.int64) if np.any(counts > 1): indices = torch.tensor(spans, device=hidden.device) batch, start, end, view = indices.unbind(1) prefix = F.pad(hidden.float().cumsum(1), (0, 0, 1, 0)) pooled = (prefix[batch, end]-prefix[batch, start])/(end-start)[:, None] view_counts = torch.tensor(np.bincount([span[3] for span in spans]), device=hidden.device) values = pooled.new_zeros(len(views), hidden.shape[-1]).index_add(0, view, pooled)/view_counts[:, None] values = F.normalize(values, dim=-1) ids = torch.tensor(group_per_view, device=hidden.device) group_counts = torch.tensor(counts, device=hidden.device) centres = values.new_zeros(len(groups), hidden.shape[-1]).index_add(0, ids, values)/group_counts[:, None] centres = F.normalize(centres, dim=-1) distances = (1-(values*centres[ids]).sum(-1)).clamp_min(0) errors = distances.new_zeros(len(groups)).index_add(0, ids, distances)/group_counts consistency = errors[group_counts > 1].mean() total = total+consistency_weight*consistency return (total,gold,labels) if return_supervision else total
@torch.inference_mode() def decode_with_transitions(self, outer, names, lengths, inputs): from shared.span_tagger import joint_constraint_tables, viterbi_paths, prediction_from_labels states, legal, start, end = joint_constraint_tables() outer_ids = torch.tensor([state[0] for state in states], device=outer.device) name_ids = torch.tensor([state[1] for state in states], device=outer.device) transitions = self.outer_transitions[outer_ids[:, None], outer_ids[None, :]] transitions = transitions+self.names_transitions[name_ids[:, None], name_ids[None, :]] initial = self.outer_start[outer_ids]+self.names_start[name_ids] final = self.outer_end[outer_ids]+self.names_end[name_ids] emissions = outer.float()[..., outer_ids]+names.float()[..., name_ids] paths = viterbi_paths(emissions, [int(length) for length in lengths], legal+self.transition_scale*transitions.cpu(), start+self.transition_scale*initial.cpu(), end+self.transition_scale*final.cpu()) return [prediction_from_labels(row['id'], row['text'], [states[s][0] for s in path], [states[s][1] for s in path]) for row, path in zip(inputs, paths, strict=True)]
@torch.inference_mode() def predict(self, features, lengths, inputs, role_threshold: float = 0.0): if self.field_presence_prior: hidden, presence = self.encode(features, lengths, inputs, return_presence=True) else: hidden = self.encode(features, lengths, inputs) outer, names = self.outer(hidden), self.names(hidden) if self.field_presence_prior: prior = self.field_presence_prior odds = torch.tensor(prior['log_prior_odds'], device=outer.device, dtype=torch.float32) eligible = torch.tensor(prior['eligible'], device=outer.device, dtype=torch.float32) evidence = (presence[:, :len(FIELDS)]-self.presence_positive_weights[:len(FIELDS)].log()-odds).clamp(-10, 10)*eligible starts = torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS], device=outer.device) outer[:, :, starts] += prior['scale']*evidence[:, None, :] results, mentions = self.decode_structures(outer, names, lengths, inputs) return self.assign_roles(inputs, results, self.role_scores(hidden, lengths, mentions), role_threshold)
@torch.inference_mode() def decode_structures(self, outer, names, lengths, inputs): index = OUTER_NAMES.index('LOCATION') outer[:, :, 1+2*index:3+2*index] = -10000 rows = [EncodedCitation(r['id'], r['text'], [0], [], [], [], None) for r in inputs] intermediate = (self.decode_with_transitions(outer, names, lengths, inputs) if self.label_transitions else structural_predictions([outer, names], rows, 1., {'structure': 'single_title'} if self.structure == 'single_title' else {})) results, mentions = [], [] for i, (row, pred) in enumerate(zip(inputs, intermediate, strict=True)): ranges = [(RANGE_TYPES.index(f['label']), f['start'], f['end'], 1.) for f in pred['fields'] if f['label'] in FIELDS] for p in pred['contributors']: ranges.append((RANGE_TYPES.index(p['kind']), p['start'], p['end'], 1.)) ranges += [(RANGE_TYPES.index(key), v['start'], v['end'], 1.) for key, v in p['name_parts'].items()] result = (prediction_from_ranges(row['id'], row['text'], ranges) if self.structure == 'single_title' else pred) result['fields'] = [f for f in result['fields'] if f['label'] in FIELDS] for person in result['contributors']: mentions.append((i, person['start'], person['end'])) results.append(result) return results, mentions
@torch.inference_mode() def assign_roles(self, inputs, results, logits, role_threshold): selected_roles = None if self.role_decoder == 'powerset': codes = (logits@self.role_masks.T+self.role_combo_bias).argmax(-1) selected_roles = self.role_masks[codes].bool().cpu() logits = logits.cpu() offset = 0 for row, result in zip(inputs, results, strict=True): for person in result['contributors']: values = logits[offset] active = selected_roles[offset] if selected_roles is not None else values > role_threshold roles = [role for role, value in zip(ROLES, active, strict=True) if value] offset += 1 person['roles'] = sorted(roles or [ROLES[int(values.argmax())]]) validate(row['text'], result) return results
class TrialHeadEnsemble(nn.Module): def __init__(self, heads: list[TrialBIO], weights: list[float]) -> None: super().__init__() if not heads or len(heads) != len(weights) or any(weight <= 0 for weight in weights): raise ValueError('invalid_head_ensemble_weights') if any(head.role_decoder != 'independent' for head in heads): raise ValueError('head_ensemble_requires_independent_role_logits') shapes = {(head.base_width, head.semantic_width, head.raw_semantic_width) for head in heads} if len(shapes) != 1: raise ValueError('head_ensemble_feature_widths_differ') self.heads = nn.ModuleList(heads) self.register_buffer('weights', torch.tensor(weights)/sum(weights)) self.role_head = nn.Identity() self.role_decoder = 'independent' self.raw_semantic_width = heads[0].raw_semantic_width
@torch.inference_mode() def predict(self, features, lengths, inputs, role_threshold=0.): hidden = [head.encode(features, lengths, inputs) for head in self.heads] outer = [head.outer(value) for head, value in zip(self.heads, hidden, strict=True)] names = [head.names(value) for head, value in zip(self.heads, hidden, strict=True)] def merged(values): return values[0] if len(values) == 1 else sum(weight*value for weight, value in zip(self.weights, values, strict=True)) results, mentions = self.heads[0].decode_structures(merged(outer), merged(names), lengths, inputs) roles = [head.role_scores(value, lengths, mentions) for head, value in zip(self.heads, hidden, strict=True)] logits = self.role_head(merged(roles)) return self.heads[0].assign_roles(inputs, results, logits, role_threshold)
class TrialPredictor: def __init__(self, package: Path, device: str = 'cuda', *, track_encoder_gradients: bool = False) -> None: self.device = device if (package/'runtime_resources.json').exists(): from shared.package_resources import RuntimeResources self.runtime_resources = RuntimeResources(package) package = self.runtime_resources.path self.base, _, _ = load_package(package, device) if (package/'adapter_model.json').exists(): from shared.bibform_trial_adapters import install_adapters, load_adapter_state adapter_settings = json.loads((package/'adapter_model.json').read_text()) install_adapters(self.base.members[0], adapter_settings) load_adapter_state(self.base.members[0], adapter_settings, package/'adapter_weights.safetensors') self.base.members[0].eval() settings = json.loads((package/'trial_model.json').read_text()) self.input_members = settings.get('input_members', [0, 1, 2, 3]) assert self.input_members and self.input_members[0] == 0 assert sorted(set(self.input_members)) == self.input_members and self.input_members[-1] <= 3 assert len(self.base.members) == len(self.input_members) def build_head() -> TrialBIO: return TrialBIO(role_weight=settings['role_weight'], context=settings['context'], sequence=settings.get('sequence', 'none'), semantic_width=128 if settings.get('semantic_features') else 0, role_decoder=settings.get('role_decoder', 'independent'), structure=settings.get('structure', 'single_title'), raw_characters=settings.get('raw_characters', False), label_transitions=settings.get('label_transitions', False), transition_scale=settings.get('transition_scale', 0.), raw_semantic_width=settings.get('raw_semantic_width', 0), attention_layers=settings.get('attention_layers', 0), role_global_context=settings.get('role_global_context', False), global_presence=settings.get('global_presence', False), hidden_width=settings.get('hidden_width', 192), role_hidden_width=settings.get('role_hidden_width', 128), role_summary_context=settings.get('role_summary_context', False), raw_context_residual=settings.get('raw_context_residual',False), additional_attention_layers=settings.get('additional_attention_layers', 0), additional_attention_scale=settings.get('additional_attention_scale', 1.)).to(device) if settings.get('head_ensemble'): heads = [] for member in settings['head_ensemble']: head = build_head() head.load_state_dict(load_file(package/member['file'], device=device)); heads.append(head) self.head = TrialHeadEnsemble(heads, [member['weight'] for member in settings['head_ensemble']]).to(device) else: self.head = build_head() self.head.load_state_dict(load_file(package/'trial_head.safetensors', device=device)) if settings.get('field_presence_prior'): prior = settings['field_presence_prior'] assert not settings.get('head_ensemble') and self.head.global_presence assert len(prior['log_prior_odds']) == len(prior['eligible']) == len(FIELDS) assert np.isfinite(prior['log_prior_odds']).all() and 0 < prior['scale'] <= 1 assert all(isinstance(value, bool) for value in prior['eligible']) self.head.field_presence_prior = prior self.head.eval() self.role_threshold = settings['role_threshold']; self.captured = {}; self.handles = [] self.trim_span_whitespace = settings.get('trim_span_whitespace', False) self.align_work_alias_roles = settings.get('align_work_alias_roles', False) self.work_alias_blocked_transfers = settings.get('work_alias_blocked_transfers', []) self.unmatched_closer_policy = settings.get('unmatched_closer_policy', []) self.count_guidance = None self.field_span_refiner = None self.name_context_refiner = None if settings.get('count_guidance'): from shared.global_field_counts import GlobalFieldCounts from shared.count_guided_predictor import CountGuidedPredictor assert not settings.get('head_ensemble') policy = settings['count_guidance'] count_model = GlobalFieldCounts(policy.get('use_soft_mass',False)).to(device) count_model.load_state_dict(load_file(package/policy['file'], device=device)) self.count_guidance = CountGuidedPredictor(count_model, policy['generation_scales'], policy['ranking_scale'], policy['minimum_gain']) if settings.get('compact_title_residual'): from shared.compact_title_residual import CompactTitleResidual assert self.count_guidance is not None policy = settings['compact_title_residual'] correction = CompactTitleResidual(policy['width']).to(device) correction.load_state_dict(load_file(package/policy['file'],device=device)) self.count_guidance.title_residual = correction.eval() self.count_guidance.title_residual_scale = policy['scale'] if settings.get('compact_field_residual'): from shared.compact_field_residual import CompactFieldResidual assert self.count_guidance is not None policy = settings['compact_field_residual'] correction = CompactFieldResidual(policy['width']).to(device) correction.load_state_dict(load_file(package / policy['file'], device=device)) self.count_guidance.field_residual = correction.eval() self.count_guidance.field_residual_scale = policy['scale'] if settings.get('field_span_refiner'): from shared.field_span_classifier import FieldSpanClassifier,FieldSpanRefiner policy=settings['field_span_refiner'] self.field_span_representation=policy.get('representation','auxiliary_characters') assert self.field_span_representation in ('auxiliary_characters','main_hidden') assert (self.input_members==[0,1,2,3] if self.field_span_representation=='auxiliary_characters' else self.count_guidance is not None) assert not policy['count_scale'] or self.count_guidance is not None span_model=FieldSpanClassifier(policy['width'],policy.get('neural_context_width',0), 192 if self.field_span_representation=='main_hidden' else 576) span_model.load_state_dict(load_file(package/policy['file'],device='cpu')) self.field_span_refiner=FieldSpanRefiner(span_model,policy['minimum_gain'],policy['count_scale'],policy['boundary_only']) if settings.get('name_context_refiner'): from shared.name_context_cnn import NameContextCNN,NameContextRefiner assert self.count_guidance is not None policy=settings['name_context_refiner'];name_model=NameContextCNN(policy['width']) name_model.load_state_dict(load_file(package/policy['file'],device='cpu')) self.name_context_refiner=NameContextRefiner(name_model,self.head,policy['residual_scale'],policy['minimum_gain']) self.compact_path_ranker = None if settings.get('compact_path_ranker'): from shared.compact_path_ranker import CompactPathRanker assert self.count_guidance is not None and self.field_span_refiner is None policy = settings['compact_path_ranker'] ranker = CompactPathRanker(policy['width']) ranker.load_state_dict(load_file(package/policy['file'],device='cpu')) self.compact_path_ranker = ranker.eval() self.path_ranker_policy = policy self.count_guidance.capture_logits = True self.compact_field_edits = None if settings.get('compact_field_edits'): from shared.compact_field_edits import CompactFieldEditRanker assert self.count_guidance is not None and self.field_span_refiner is not None assert self.field_span_representation == 'main_hidden' assert self.field_span_refiner.model.neural_context_width == 0 policy = settings['compact_field_edits'] model = CompactFieldEditRanker(policy['width']) model.load_state_dict(load_file(package/policy['file'],device='cpu')) self.compact_field_edits = model.eval() self.field_edit_threshold = policy['minimum_score'] self.field_edit_merges = policy.get('merges',False) self.field_edit_contextual = policy.get('contextual',False) self.field_edit_options = {'expanded_boundaries':True} if policy.get('expanded_boundaries') else {} self.count_guidance.capture_logits = True for i, member in enumerate(self.base.members): def capture(module, args, index=i): self.captured[index] = args[0] if track_encoder_gradients else args[0].detach() self.handles.append(member.heads[0].register_forward_pre_hook(capture)) self.semantic_projection = None self.character_proxy = None self.character_feature_blend = settings.get('compact_character_feature_blend') if settings.get('compact_character_proxy'): from shared.compact_character_proxy import CompactCharacterProxy expected_members = [0] if self.character_feature_blend is None else [0,3] assert self.input_members == expected_members and settings.get('compact_semantic_bridge') and settings.get('semantic_features') if self.character_feature_blend is not None and not 0. <= self.character_feature_blend <= 1.: raise ValueError('invalid_character_feature_blend') width = self.base.members[0].encoder.config.hidden_size depth = settings.get('compact_character_proxy_contextual_depth', 0) proxy = CompactCharacterProxy(width, contextual_depth=depth) if depth else CompactCharacterProxy(width) self.character_proxy = proxy.to(device) self.character_proxy.load_state_dict(load_file(package/settings['compact_character_proxy'], device=device)) self.character_proxy.eval() if settings.get('semantic_features'): self.semantic_projection = {key: value.to(device) for key, value in load_file(package/'semantic_projection.safetensors').items()} semantic_width = len(self.semantic_projection['mean']) bridge = None if settings.get('compact_semantic_bridge'): bridge = {key: value.float() for key, value in load_file(package/settings['compact_semantic_bridge'], device=device).items()} semantic_width = bridge['weight'].shape[1] if bridge['weight'].shape[0] != len(self.semantic_projection['mean']): raise ValueError('compact_semantic_bridge_output_width_mismatch') def capture_semantics(module, args): contextual = args[0][..., :semantic_width] if not track_encoder_gradients: contextual = contextual.detach() if self.character_proxy is not None: self.captured['proxy_context'] = contextual if bridge is not None: contextual = F.linear(contextual, bridge['weight'], bridge['bias']) self.captured['semantic'] = contextual self.handles.append(self.base.members[0].projection.register_forward_pre_hook(capture_semantics))
def _encode_characters(self, chunk): rows = [EncodedCitation(r['id'], r['text'], [0], [], [], [], None) for r in chunk] self.base.member_text_outputs(rows, self.device) active = dict(zip(self.input_members, range(len(self.input_members)), strict=True)) lengths = torch.tensor([len(r['text']) for r in chunk], device=self.device) components = [self.captured[active[i]] if i in active else torch.zeros_like(self.captured[0]) for i in range(4)] if self.character_proxy is not None: context = self.captured['proxy_context'] mask = torch.arange(context.shape[1], device=self.device)[None,:] < lengths[:,None] proxy = self.character_proxy(components[0].half().float(), context, mask) components[3] = (proxy if self.character_feature_blend is None else proxy.lerp(components[3].float(), self.character_feature_blend)) features = torch.cat(components, -1).half().float() if self.semantic_projection is not None: extra = ((self.captured['semantic'].float()-self.semantic_projection['mean'])@ self.semantic_projection['components'].T).half().float() features = torch.cat([features, extra], -1) if self.head.raw_semantic_width: features = torch.cat([features, self.captured['semantic'].half().float()], -1) return features, lengths
@torch.inference_mode() def predict(self, inputs, batch_size: int = 16, *, feature_cache=None): if batch_size < 1: raise ValueError('batch_size_must_be_positive') if any(set(r) != {'id', 'text'} or not isinstance(r['id'], str) or not isinstance(r['text'], str) or not r['text'] for r in inputs): raise ValueError('only_original_id_and_text_are_accepted') if len({r['id'] for r in inputs}) != len(inputs): raise ValueError('duplicate_input_id') result = {} ordered = sorted(inputs, key=lambda r: len(r['text'])) for begin in range(0, len(ordered), batch_size): chunk = ordered[begin:begin+batch_size] if feature_cache is None: features, lengths = self._encode_characters(chunk) else: key = (self, self.character_feature_blend, tuple((row['id'], row['text']) for row in chunk)) if key not in feature_cache: feature_cache[key] = self._encode_characters(chunk) features, lengths = feature_cache[key] texts = {row['id']: row['text'] for row in chunk} predicted = (self.count_guidance.predict(self.head, features, lengths, chunk, self.role_threshold, self._postprocess) if self.count_guidance is not None else self.head.predict(features, lengths, chunk, self.role_threshold)) if self.count_guidance is None: predicted=[self._postprocess(texts[row['id']],row) for row in predicted] if self.field_span_refiner is not None: count_logp=self.count_guidance.last_count_logp if self.count_guidance is not None else None neural_context=self.count_guidance.last_global_features if self.count_guidance is not None else None span_features=(self.count_guidance.last_hidden if self.field_span_representation=='main_hidden' else features) predicted=self.field_span_refiner.predict(span_features,chunk,predicted,count_logp,neural_context) if self.name_context_refiner is not None: predicted=self.name_context_refiner.predict(self.count_guidance.last_hidden,self.head,chunk,predicted) if self.compact_path_ranker is not None: from shared.compact_path_ranker import candidate_rows,comparisons guide = self.count_guidance alternatives = candidate_rows(self.head,guide.last_logits,guide.last_hidden,lengths,chunk, self.role_threshold,self._postprocess,self.name_context_refiner, self.path_ranker_policy['paths']) vectors = comparisons(predicted,alternatives,guide.last_logits,guide.last_count_logp,lengths) predicted = self.compact_path_ranker.predict(predicted,vectors,self.path_ranker_policy['minimum_score']) if self.compact_field_edits is not None: predicted = self.compact_field_edits.predict(chunk,predicted,self.count_guidance, self.field_span_refiner.model,self.field_edit_threshold, self.field_edit_merges,self.field_edit_contextual,**self.field_edit_options) for row in predicted: result[row['id']] = row return [result[r['id']] for r in inputs]
def _postprocess(self, text, row): if self.trim_span_whitespace: from shared.bibform_trial import trim_whitespace_boundaries row = trim_whitespace_boundaries(text, row) if self.align_work_alias_roles: from shared.bibform_trial import align_work_alias_roles row = align_work_alias_roles(row, self.work_alias_blocked_transfers) if self.unmatched_closer_policy: from shared.bibform_trial import trim_unmatched_closing_boundaries row = trim_unmatched_closing_boundaries(text, row, self.unmatched_closer_policy) return row1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Extract citations from UTF-8 bytes aligned to the original character positions."""
import numpy as npimport torchfrom torch import nn
from shared.bibform_trial import trim_whitespace_boundariesfrom shared.bibform_trial_model import TrialBIO,utf8_character_idsfrom shared.range_extraction import position_features
WIDTH = 144DEPTH = 8
def pack_bytes(rows,device): lengths = [len(row['text']) for row in rows] if not lengths or min(lengths)==0: raise ValueError('byte_extractor_requires_nonempty_text') values = np.zeros((len(rows),max(lengths),4),dtype=np.int64) for index,row in enumerate(rows): values[index,:lengths[index]] = utf8_character_ids(row['text']) return torch.from_numpy(values).to(device),torch.tensor(lengths,device=device)
class CompactByteExtractor(nn.Module): def __init__(self,width=WIDTH,depth=DEPTH): super().__init__() self.width = width self.bytes = nn.Embedding(257,24,padding_idx=0) self.project = nn.Linear(4*24,width) self.local = nn.ModuleList(nn.Conv1d(width,width,3,padding=dilation,dilation=dilation) for dilation in (1,2,4)) self.local_norm = nn.ModuleList(nn.LayerNorm(width) for _ in self.local) self.layers = nn.ModuleList(nn.TransformerEncoderLayer( width,6,dim_feedforward=2*width,dropout=.08,activation='gelu',batch_first=True,norm_first=True) for _ in range(depth)) self.norm = nn.LayerNorm(width) self.head = TrialBIO(width=width,hidden_width=width,role_hidden_width=96, structure='unrestricted',label_transitions=True, transition_scale=.25,role_decoder='powerset',boundary_weight=2.3, structural_loss='reference_mean')
def encode(self,byte_ids,lengths): width = byte_ids.size(1) padding = torch.arange(width,device=byte_ids.device)[None,:]>=lengths[:,None] valid = ~padding[...,None] hidden = self.project(self.bytes(byte_ids).flatten(-2))*valid for convolution,norm in zip(self.local,self.local_norm,strict=True): local = torch.nn.functional.gelu(convolution(norm(hidden).transpose(1,2)).transpose(1,2)) hidden = (hidden+local)*valid hidden = (hidden+.18*position_features(width,self.width,hidden.device)[None,...])*valid for layer in self.layers: hidden = layer(hidden,src_key_padding_mask=padding)*valid return self.norm(hidden)*valid
@torch.inference_mode() def predict(self,rows,device): raw,lengths = pack_bytes(rows,device) features = self.encode(raw,lengths) return [trim_whitespace_boundaries(row['text'],result) for row,result in zip(rows,self.head.predict(features,lengths,rows),strict=True)]12345678910111213141516171819202122232425262728293031323334353637383940"""A small character branch using the compact encoder's existing context."""
import torchfrom torch import Tensor, nnfrom torch.nn import functional as F
class CompactCharacterProxy(nn.Module): def __init__(self, context_width: int, character_width: int = 192, contextual_depth: int = 0) -> None: super().__init__() self.input = nn.Linear(context_width + character_width, character_width) self.blocks = nn.ModuleList(nn.Conv1d(character_width, character_width, 3, padding=d, dilation=d) for d in (1, 2, 4)) self.norms = nn.ModuleList(nn.LayerNorm(character_width) for _ in self.blocks) self.output = nn.Linear(character_width, character_width) nn.init.zeros_(self.output.weight) nn.init.zeros_(self.output.bias) self.context_blocks = nn.ModuleList( nn.TransformerEncoderLayer(character_width, nhead=4, dim_feedforward=4*character_width, dropout=.1, activation='gelu', batch_first=True, norm_first=True) for _ in range(contextual_depth) ) if self.context_blocks: self.context_output = nn.Linear(character_width, character_width) nn.init.zeros_(self.context_output.weight) nn.init.zeros_(self.context_output.bias)
def forward(self, characters: Tensor, context: Tensor, valid: Tensor) -> Tensor: mask = valid.unsqueeze(-1) hidden = self.input(torch.cat((characters, context), -1)) * mask for conv, norm in zip(self.blocks, self.norms, strict=True): update = F.gelu(conv(hidden.transpose(1,2)).transpose(1,2)) hidden = norm(hidden + update) * mask result = self.output(hidden) if self.context_blocks: full_context = hidden for block in self.context_blocks: full_context = block(full_context, src_key_padding_mask=~valid) * mask result = result + self.context_output(full_context) return result * mask1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Predict the end of a detected edition while keeping its original start."""
import numpy as npimport torchfrom torch import nn
from shared.bibform_trial_model import RawCharacterEncoder, utf8_character_idsfrom shared.dataset_schema import visible_value
EDITION_RADIUS = 12
class CompactEditionEndpoint(nn.Module): def __init__(self): super().__init__() self.encoded = nn.Linear(192,64) self.bytes = RawCharacterEncoder(64,(1,2)) self.endpoint = nn.Sequential(nn.LayerNorm(193),nn.Linear(193,64),nn.GELU(),nn.Linear(64,1))
def forward(self,hidden,lengths,rows,starts): values = np.zeros((*hidden.shape[:2],4),dtype=np.int64) for i,row in enumerate(rows): values[i,:len(row['text'])] = utf8_character_ids(row['text']) state = self.encoded(hidden) + self.bytes(torch.from_numpy(values).to(hidden.device),lengths) span_start = state[torch.arange(len(rows),device=hidden.device),starts] edge = torch.zeros_like(state[:,:1]) left = torch.cat((edge,state),1) right = torch.cat((state,edge),1) positions = torch.arange(left.size(1),device=hidden.device)[None,:] distance = ((positions-starts[:,None]).clamp(-32,64)/64.)[...,None] return self.endpoint(torch.cat((left,right,span_start[:,None,:].expand_as(left),distance),-1)).squeeze(-1)
def edition(row): matches = [field for field in row['fields'] if field['label']=='EDITION'] return matches[0] if len(matches)==1 else None
def end_positions(text,prediction,edition): left,right = edition['start'],edition['end'] blockers = [*prediction['fields'],*prediction['contributors']] stop = min((part['start'] for part in blockers if part['start']>=right),default=len(text)) begin = max(left+1,right-EDITION_RADIUS) end = min(stop,right+EDITION_RADIUS) return [offset for offset in range(begin,end+1) if not text[offset-1].isspace()]
def edition_edit(row,prediction,edition,scores): old = edition['end'] positions = [offset for offset in end_positions(row['text'],prediction,edition) if offset!=old] if not positions: return None chosen = max(positions,key=lambda offset:float(scores[offset])) value = visible_value(row['text'][edition['start']:chosen],'EDITION') adjusted = {**edition,'end':chosen,'value':value} result = {**prediction,'fields':[adjusted if field is edition else field for field in prediction['fields']]} return float(scores[chosen]-scores[old]),result
@torch.inference_mode()def refine_edition_endpoints(rows,predictions,hidden,model,threshold): editions = [(i,edition(prediction)) for i,prediction in enumerate(predictions)] valid = [(i,field) for i,field in editions if field is not None] if not valid: return predictions indices,fields = zip(*valid,strict=True) raw = [rows[i] for i in indices] lengths = torch.tensor([len(row['text']) for row in raw],device=hidden.device) starts = torch.tensor([field['start'] for field in fields],device=hidden.device) scores = model(hidden[list(indices)].float(),lengths,raw,starts).float().cpu().numpy() updated = list(predictions) for index,field,score in zip(indices,fields,scores,strict=True): proposal = edition_edit(rows[index],predictions[index],field,score) if proposal is not None and proposal[0]>threshold: updated[index] = proposal[1] return updated123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Choose between frozen extraction predictions using both models' character scores."""
import numpy as npimport torch
from shared.bibform_trial import ROLES, signaturefrom shared.compact_path_ranker import difference_vector
def enable_model_selection(models): for model in models: if model.count_guidance is None: raise ValueError('model_selection_requires_character_scores') model.count_guidance.capture_logits = True
def combine_fields_and_contributors(field_predictions, contributor_predictions): combined = [] for fields, people in zip(field_predictions, contributor_predictions, strict=True): if fields['id'] != people['id']: raise ValueError('context_predictions_returned_different_ids') contributors = people['contributors'] if any(field['start'] < person['end'] and person['start'] < field['end'] for field in fields['fields'] for person in contributors): combined.append(fields) else: combined.append({**fields, 'contributors': contributors}) return combined
def role_confidence(model, rows, predictions, disagreements): hidden = model.count_guidance.last_hidden lengths = torch.tensor([len(row['text']) for row in rows], device=hidden.device) mentions, assignments = [], [] for index in disagreements: for person in predictions[index]['contributors']: mentions.append((index, person['start'], person['end'])) assignments.append([role in person['roles'] for role in ROLES]) if not mentions: return {index: np.zeros(len(ROLES) + 2, dtype=np.float32) for index in disagreements} logits = model.head.role_scores(hidden, lengths, mentions).float() - model.role_threshold signs = torch.tensor(assignments, device=logits.device, dtype=logits.dtype) * 2 - 1 scores = torch.nn.functional.logsigmoid(logits * signs).cpu().numpy() result = {} offset = 0 for index in disagreements: count = len(predictions[index]['contributors']) if count: confidence = scores[offset:offset + count] result[index] = np.concatenate((confidence.mean(0), [confidence.min(), confidence.max()])) else: result[index] = np.zeros(len(ROLES) + 2, dtype=np.float32) offset += count return result
@torch.inference_mode()def model_comparisons(models, inputs, *, role_evidence=False, auxiliary_predictions=None, primary_feature_cache=None): rows = sorted(inputs, key=lambda row:len(row['text'])) primary, auxiliary = models base = (primary.predict(rows, len(rows)) if primary_feature_cache is None else primary.predict(rows, len(rows), feature_cache=primary_feature_cache)) if auxiliary_predictions is None: alternative = auxiliary.predict(rows, len(rows)) else: alternative = auxiliary_predictions if any(row['id'] != prediction['id'] for row, prediction in zip(rows, alternative, strict=True)): raise ValueError('auxiliary_predictions_returned_different_ids') disagreements = [i for i,(before,after) in enumerate(zip(base,alternative,strict=True)) if signature(before)!=signature(after)] vectors = {} if disagreements: evidence = [] for model in models: guide = model.count_guidance evidence.append((tuple(t.float().log_softmax(-1).cpu().numpy() for t in guide.last_logits), guide.last_count_logp)) role_differences = [] if role_evidence: for model in models: before = role_confidence(model, rows, base, disagreements) after = role_confidence(model, rows, alternative, disagreements) role_differences.append({i: after[i] - before[i] for i in disagreements}) for i in disagreements: length = len(rows[i]['text']) signals = [difference_vector(base[i],alternative[i], tuple(logits[i,:length] for logits in scores), counts[i],0) for scores,counts in evidence] signals.extend(difference[i] for difference in role_differences) vectors[i] = np.concatenate(signals) return base, alternative, vectors
@torch.inference_mode()def choose_predictions(models, inputs, selector, threshold, *, role_evidence=False, auxiliary_predictions=None, primary_feature_cache=None): base, alternative, vectors = model_comparisons(models, inputs, role_evidence=role_evidence, auxiliary_predictions=auxiliary_predictions, primary_feature_cache=primary_feature_cache) if vectors: scores = selector(torch.from_numpy(np.stack(list(vectors.values())))).tolist() for index,score in zip(vectors,scores,strict=True): if score > threshold: base[index] = alternative[index] return base123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Score plausible alternative character paths using their model evidence."""from collections import Counter
import numpy as npimport torchfrom torch import nn
from shared.bibform_trial import FIELDS, ROLES, signaturefrom shared.count_guided_candidates import count_vectorfrom shared.dataset_schema import bio_labelsfrom shared.kbest_viterbi import kbest_viterbifrom shared.span_tagger import (NAME_NAMES, OUTER_NAMES, joint_constraint_tables, prediction_from_labels)
def _bio(row: dict, length: int) -> tuple[np.ndarray, np.ndarray]: outer = [(f['label'], f['start'], f['end']) for f in row['fields']] outer.extend((p['kind'],p['start'],p['end']) for p in row['contributors']) names = [(key, span['start'],span['end']) for p in row['contributors'] for key,span in p['name_parts'].items()] return np.asarray(bio_labels(length,outer,OUTER_NAMES)),np.asarray(bio_labels(length,names,NAME_NAMES))
def difference_vector(baseline: dict, candidate: dict, likelihoods: tuple[np.ndarray,np.ndarray], count_logp: np.ndarray, rank: int) -> np.ndarray: length = len(likelihoods[0]) before = _bio(baseline,length) after = _bio(candidate,length) old_counts,new_counts = count_vector(baseline),count_vector(candidate) labels = np.arange(len(FIELDS)) values = [np.log1p(length),float(rank)] values.extend((count_logp[labels,new_counts]-count_logp[labels,old_counts]) / 10.) values.extend((new_counts-old_counts).tolist()) for old,new,score,category_count in zip(before,after,likelihoods,(len(OUTER_NAMES),len(NAME_NAMES)),strict=True): changed = np.flatnonzero(old!=new) if len(changed): a,b = score[changed,old[changed]],score[changed,new[changed]] delta = b-a values.extend((len(changed)/10,changed[0]/length,changed[-1]/length, delta.sum()/10,delta.mean(),delta.min(),delta.max(),a.mean(),b.mean())) else: values.extend([0.]*9) old_class = (old+1)//2 new_class = (new+1)//2 for label in range(1,category_count+1): leaving = (old_class==label) & (old!=new) arriving = (new_class==label) & (old!=new) values.extend((int(leaving.sum())/10,int(arriving.sum())/10)) roles_a = Counter(role for p in baseline['contributors'] for role in p['roles']) roles_b = Counter(role for p in candidate['contributors'] for role in p['roles']) values.extend(roles_b[r]-roles_a[r] for r in ROLES) return np.asarray(values,dtype=np.float32)
@torch.inference_mode()def candidate_rows(head, logits: tuple, hidden: torch.Tensor, lengths: torch.Tensor, rows: list[dict], threshold: float, postprocess, name_refiner, k: int) -> list[list[tuple[int,dict]]]: outer,names = logits states, legal, initial, final = joint_constraint_tables() outer_ids = torch.as_tensor([s[0] for s in states],device=outer.device) name_ids = torch.as_tensor([s[1] for s in states],device=outer.device) location = OUTER_NAMES.index('LOCATION') work = outer.float().clone() work[:,:,1+2*location:3+2*location] = -10000. emissions = work[...,outer_ids] + names.float()[...,name_ids] transitions = head.outer_transitions[outer_ids[:,None],outer_ids[None,:]]+head.names_transitions[name_ids[:,None],name_ids[None,:]] start = head.outer_start[outer_ids]+head.names_start[name_ids] end = head.outer_end[outer_ids]+head.names_end[name_ids] allowed = legal+head.transition_scale*transitions.cpu() paths = kbest_viterbi(emissions,lengths.tolist(),allowed,initial+head.transition_scale*start.cpu(), final+head.transition_scale*end.cpu(),k) result = [[] for _ in rows] for rank in range(k): indices, raw, subset = [], [], [] for i,(row,choices) in enumerate(zip(rows,paths,strict=True)): if rank >= len(choices): continue choice = choices[rank] pred = prediction_from_labels(row['id'],row['text'],[states[z][0] for z in choice], [states[z][1] for z in choice]) pred['fields'] = [f for f in pred['fields'] if f['label'] in FIELDS] indices.append(i); raw.append(pred); subset.append(row) if not indices: continue mention = [(i,p['start'],p['end']) for i,pred in enumerate(raw) for p in pred['contributors']] features, sizes = hidden[indices], lengths[indices] assigned = head.assign_roles(subset,raw,head.role_scores(features,sizes,mention),threshold) assigned = [postprocess(row['text'],pred) for row,pred in zip(subset,assigned,strict=True)] if name_refiner: assigned = name_refiner.predict(features,head,subset,assigned) for i,pred in zip(indices,assigned,strict=True): result[i].append((rank,pred)) return result
def comparisons(baseline: list[dict], candidates: list[list[tuple[int,dict]]], logits: tuple, count_logp: np.ndarray, lengths: torch.Tensor) -> list[list[tuple[dict,np.ndarray]]]: rows = [] log_probability = tuple(score.float().log_softmax(-1).cpu().numpy() for score in logits) for i,(before,variants,length) in enumerate(zip(baseline,candidates,lengths.tolist(),strict=True)): known = {signature(before)} evidence = tuple(values[i,:length] for values in log_probability) alternatives = [] for rank,after in variants: difference = signature(after) if difference in known: continue known.add(difference) alternatives.append((after,difference_vector(before,after,evidence,count_logp[i],rank))) rows.append(alternatives) return rows
class CompactPathRanker(nn.Module): def __init__(self, width: int) -> None: super().__init__() self.register_buffer('mean',torch.zeros(width)) self.register_buffer('scale',torch.ones(width)) self.regression = nn.Linear(width,1)
def forward(self, values: torch.Tensor) -> torch.Tensor: return self.regression(((values-self.mean)/self.scale).clamp(-8.,8.)).squeeze(-1)
@torch.inference_mode() def predict(self, baseline: list[dict], alternatives: list[list[tuple[dict,np.ndarray]]], minimum_score: float) -> list[dict]: flattened = [vector for variants in alternatives for _,vector in variants] if not flattened: return baseline scores = self(torch.from_numpy(np.stack(flattened))).tolist() selected=[] offset=0 for old,variants in zip(baseline,alternatives,strict=True): if variants: best=max(range(len(variants)),key=lambda i:scores[offset+i]) selected.append(variants[best][0] if scores[offset+best]>minimum_score else old) offset+=len(variants) else: selected.append(old) return selected12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Blend character-level extraction scores from two frozen models."""
import torch
from shared.global_field_counts import field_start_mass
def enable_score_blending(baseline, auxiliary): for predictor in (baseline, auxiliary): if (predictor.count_guidance is None or predictor.compact_path_ranker is not None or predictor.compact_field_edits is not None): raise ValueError('unsupported_score_blend_model') predictor.count_guidance.capture_logits = True if baseline.field_span_refiner is not None and baseline.field_span_representation != 'main_hidden': raise ValueError('unsupported_score_blend_span_refiner')
@torch.inference_mode()def decode_cached_scores(model, rows, outer, names): guide = model.count_guidance hidden = guide.last_hidden lengths = torch.tensor([len(row['text']) for row in rows], device=hidden.device) mass = field_start_mass(outer, lengths) if guide.model.use_soft_mass else None result = guide.predict_from_scores(model.head, hidden, outer, names, lengths, rows, model.role_threshold, model._postprocess, mass) if model.field_span_refiner is not None: if model.field_span_representation != 'main_hidden': raise ValueError('unsupported_score_blend_span_refiner') result = model.field_span_refiner.predict(hidden, rows, result, guide.last_count_logp, guide.last_global_features) if model.name_context_refiner is not None: result = model.name_context_refiner.predict(hidden, model.head, rows, result) return result
@torch.inference_mode()def score_blends(baseline, auxiliary, inputs, weights): rows = sorted(inputs, key=lambda row:len(row['text'])) reference = baseline.predict(rows, len(rows)) predictions = {0.:reference} if not any(weights): return predictions auxiliary.predict(rows, len(rows)) base_outer, base_names = baseline.count_guidance.last_logits extra_outer, extra_names = auxiliary.count_guidance.last_logits for weight in weights: if not weight: continue outer = base_outer.lerp(extra_outer, weight) names = base_names.lerp(extra_names, weight) predictions[weight] = decode_cached_scores(baseline, rows, outer, names) return predictions1234567891011121314151617181920212223242526272829303132333435363738394041"""Compare support for an absorbed title span in both frozen extractors."""
import numpy as npimport torch
from shared.compact_path_ranker import difference_vector
MERGE_ACTION = 'absorb_fields'MINIMUM_POINTER_MARGIN = -3.
@torch.inference_mode()def title_merge_signals(rows, baseline, alternatives, models, upper_margin=None): pending = [(i,*choices[MERGE_ACTION]) for i,choices in enumerate(alternatives) if MERGE_ACTION in choices and MINIMUM_POINTER_MARGIN<choices[MERGE_ACTION][0] and (upper_margin is None or choices[MERGE_ACTION][0]<=upper_margin)] if not pending: return evidence = [ (tuple(value.float().log_softmax(-1).cpu().numpy() for value in model.count_guidance.last_logits), model.count_guidance.last_count_logp) for model in models ] for i,margin,candidate in pending: length = len(rows[i]['text']) signals = [difference_vector(baseline[i],candidate,tuple(score[i,:length] for score in scores),counts[i],0) for scores,counts in evidence] yield i,candidate,np.concatenate((np.asarray([margin],dtype=np.float32),*signals))
@torch.inference_mode()def choose_supported_title_merges(rows, predictions, options, models, selector, threshold): alternatives = list(title_merge_signals(rows,predictions,options,models)) result = list(predictions) if alternatives: scores = selector(torch.from_numpy(np.stack([signal for _,_,signal in alternatives]))).tolist() for (index,proposal,_),score in zip(alternatives,scores,strict=True): if score>threshold: result[index] = proposal return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Score complete title spans from a frozen character representation."""
import numpy as npimport torchfrom torch import nn
from shared.dataset_schema import visible_value
TITLE_ACTIONS = ('absorb_fields', 'expand', 'shrink')TITLE_POINTER_WIDTH = 96
class CompactTitlePointer(nn.Module): def __init__(self, width=TITLE_POINTER_WIDTH): super().__init__() self.character = nn.Linear(192,width) self.boundary = nn.Sequential(nn.LayerNorm(3*width+1),nn.Linear(3*width+1,width),nn.GELU()) self.unary = nn.Linear(width,2) self.start_query = nn.Linear(width,32) self.end_key = nn.Linear(width,32)
def forward(self, hidden, lengths): features = self.character(hidden) offsets = torch.arange(features.size(1)+1,device=features.device) mask = offsets[:-1][None,:] < lengths[:,None] features = features * mask[...,None] edge = torch.zeros_like(features[:,:1]) before = torch.cat((edge,features),dim=1) after = torch.cat((features,edge),dim=1) context = (features.sum(1)/lengths[:,None])[:,None].expand_as(before) position = offsets[None,:].expand(hidden.size(0),-1) / lengths[:,None] boundary = self.boundary(torch.cat((before,after,context,position[...,None]),dim=-1)) unary = self.unary(boundary) return unary[...,0],unary[...,1],self.start_query(boundary)/np.sqrt(32),self.end_key(boundary)
def boundary_masks(rows, width, device): start = np.zeros((len(rows),width),dtype=bool) end = np.zeros_like(start) for i,row in enumerate(rows): visible = [not char.isspace() for char in row['text']] length = len(visible) start[i,:length] = visible end[i,1:length+1] = visible return torch.from_numpy(start).to(device),torch.from_numpy(end).to(device)
def title_alternatives(text, baseline, scores, actions=TITLE_ACTIONS): titles = [(i,f) for i,f in enumerate(baseline['fields']) if f['label']=='TITLE'] if len(titles) != 1: return {} title_index, title = titles[0] old_start, old_end = title['start'],title['end'] other = [(i,f['start'],f['end']) for i,f in enumerate(baseline['fields']) if i!=title_index] people = [(p['start'],p['end']) for p in baseline['contributors']] left,right,query,key = scores starts = np.array([n for n in range(max(0,old_start-12),min(len(text),old_start+13)) if not text[n].isspace()],dtype=np.int64) ends = np.array([n for n in range(max(1,old_end-100),min(len(text),old_end+100)+1) if not text[n-1].isspace()],dtype=np.int64) if not len(starts) or not len(ends): return {} values = (left[starts,None]+right[None,ends]+query[starts]@key[ends].T) valid = starts[:,None]<ends[None,:] # Only propose intervals that overlap the detected title and preserve every contributor. valid &= (starts[:,None]<old_end) & (ends[None,:]>old_start) for begin,finish in people: valid &= (starts[:,None]>=finish) | (ends[None,:]<=begin) absorbed = np.zeros_like(valid) for _,begin,finish in other: overlap = (starts[:,None]<finish) & (ends[None,:]>begin) contained = (starts[:,None]<=begin) & (ends[None,:]>=finish) valid &= (~overlap | contained) absorbed |= contained base = float(left[old_start]+right[old_end]+query[old_start]@key[old_end]) valid &= (starts[:,None]!=old_start) | (ends[None,:]!=old_end) expanding = (starts[:,None]<old_start) | (ends[None,:]>old_end) variants = {} for action,mask in zip(TITLE_ACTIONS,(absorbed,~absorbed & expanding,~absorbed & ~expanding),strict=True): if action not in actions: continue allowed = valid & mask if not allowed.any(): continue ranked = np.where(allowed,values,-np.inf) i,j = np.unravel_index(ranked.argmax(),ranked.shape) start,end = int(starts[i]),int(ends[j]) dropped = {p for p,a,b in other if start<=a and b<=end} result = [f for p,f in enumerate(baseline['fields']) if p!=title_index and p not in dropped] result.append({'label':'TITLE','start':start,'end':end,'value':visible_value(text[start:end],'TITLE')}) result.sort(key=lambda field:field['start']) variants[action] = (float(ranked[i,j])-base,{**baseline,'fields':result}) return variants
@torch.inference_mode()def title_comparisons(rows, predictions, hidden, pointer, actions=TITLE_ACTIONS): lengths = torch.tensor([len(row['text']) for row in rows],device=hidden.device) tensors = pointer(hidden.float(),lengths) scores = [tensor.float().cpu().numpy() for tensor in tensors] return [title_alternatives(row['text'],pred,tuple(array[i] for array in scores),actions) for i,(row,pred) in enumerate(zip(rows,predictions,strict=True))]
def apply_title_comparisons(predictions, alternatives, thresholds): adjusted = [] for baseline,options in zip(predictions,alternatives,strict=True): eligible = [(score-thresholds[action],action,proposal) for action,(score,proposal) in options.items() if action in thresholds and score>thresholds[action]] adjusted.append(max(eligible)[2] if eligible else baseline) return adjusted1234567891011121314151617"""Expand a rowwise int8 extraction head in its isolated runtime directory."""
from pathlib import Path
from safetensors.torch import load_file, save_file
from shared.weight_storage import decode_int8_weights
def decode_trial_head(package: Path) -> None: head = package/'trial_head.safetensors' if head.is_symlink(): raise ValueError('expected_a_temporary_trial_head') decoded = decode_int8_weights(load_file(head)) temporary = head.with_suffix('.decoded') save_file(decoded,temporary) temporary.replace(head)1234567891011121314151617181920212223242526272829303132333435363738"""Distinguish version values from volume values without changing span offsets."""
import numpy as npimport torch
from shared.dataset_schema import visible_valuefrom shared.field_span_classifier import span_descriptors
@torch.inference_mode()def reclassify_version_spans(rows, predictions, hidden, classifier, threshold): coordinates, descriptors = [], [] for i, (source,prediction) in enumerate(zip(rows,predictions,strict=True)): if source['id'] != prediction['id']: raise ValueError('version_span_prediction_misaligned') fields = [(j,field['start'],field['end']) for j,field in enumerate(prediction['fields']) if field['label']=='VOLUME'] if not fields: continue text = source['text'] characters = hidden[i,:len(text)].float().cpu().numpy() vectors = span_descriptors(characters,[(start,end) for _,start,end in fields],character_width=192) coordinates.extend((i,j,start,end) for j,start,end in fields) descriptors.extend(vectors) if not coordinates: return predictions result = list(predictions) copies = {} scores = classifier(torch.from_numpy(np.asarray(descriptors,dtype=np.float32))).tolist() for (i,j,start,end), score in zip(coordinates,scores,strict=True): if score <= threshold: continue if i not in copies: copies[i] = list(predictions[i]['fields']) result[i] = {**predictions[i],'fields':copies[i]} original = rows[i]['text'][start:end] copies[i][j] = {'label':'VERSION','start':start,'end':end,'value':visible_value(original,'VERSION')} return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Share identical resources and losslessly store differences between model packages."""
from compression import zstdimport hashlibimport jsonfrom pathlib import Path
import numpy as np
from shared.package_resources import RuntimeResources
def resource_contents(package: Path) -> dict[Path, bytes]: resources = RuntimeResources(package) try: return {path.relative_to(resources.path):read_resource(path) for path in resources.path.rglob('*') if path.is_file() and path.name not in ('runtime_resources.json', 'runtime_resources.tar.zst')} finally: resources.temporary.cleanup()
def read_resource(path: Path) -> bytes: content = path.read_bytes() return zstd.decompress(content) if path.name.endswith('.safetensors.zst') else content
def encode_delta(previous: bytes | None, content: bytes, level: int = 9) -> tuple[str, bytes]: if previous == content: return 'shared', b'' compressed = zstd.compress(content, level=level) if previous is not None and len(previous) == len(content): base = np.frombuffer(previous, dtype=np.uint8) current = np.frombuffer(content, dtype=np.uint8) delta = zstd.compress((current-base).tobytes(), level=level) if len(delta) < len(compressed): return 'byte_delta', delta return 'compressed_full', compressed
def decode_delta(method: str, previous: bytes | None, payload: bytes) -> bytes: if method == 'compressed_full': return zstd.decompress(payload) if previous is None: raise ValueError('missing_base_resource') if method == 'shared': return previous if method != 'byte_delta': raise ValueError('invalid_resource_encoding') delta = zstd.decompress(payload) if len(delta) != len(previous): raise ValueError('invalid_resource_delta_size') return (np.frombuffer(previous, dtype=np.uint8) + np.frombuffer(delta, dtype=np.uint8)).tobytes()
def prepare_delta_model(baseline: dict[Path, bytes], candidate: dict[Path, bytes], folder: Path | None = None, level: int = 9) -> dict: inventory = {} if folder is not None: folder.mkdir() for index, (path, content) in enumerate(sorted(candidate.items())): previous = baseline.get(path) method, payload = encode_delta(previous, content, level=level) if decode_delta(method, previous, payload) != content: raise ValueError(f'resource_delta_failed_roundtrip:{path}') entry = {'bytes':len(payload), 'method':method, 'sha256':hashlib.sha256(content).hexdigest()} if payload and folder is not None: entry['payload'] = f'{index:03d}.zst' (folder/entry['payload']).write_bytes(payload) inventory[path.as_posix()] = entry if folder is not None: (folder/'manifest.json').write_text(json.dumps(inventory, sort_keys=True)+'\n') return {'resources':inventory, 'removed_resources':sorted(path.as_posix() for path in baseline.keys()-candidate.keys()), 'payload_bytes':sum(entry['bytes'] for entry in inventory.values())}
def restore_delta_model(baseline: Path, folder: Path, target: Path) -> None: resources = RuntimeResources(baseline) try: manifest = json.loads((folder/'manifest.json').read_text()) for name, entry in manifest.items(): relative = Path(name) if relative.is_absolute() or '..' in relative.parts or not relative.name: raise ValueError('invalid_delta_resource_path') base_path = resources.path/relative previous = read_resource(base_path) if base_path.is_file() else None payload_name = entry.get('payload') if payload_name and Path(payload_name).name != payload_name: raise ValueError('invalid_delta_payload_path') payload = (folder/payload_name).read_bytes() if payload_name else b'' if len(payload) != entry['bytes']: raise ValueError('invalid_delta_payload_size') content = decode_delta(entry['method'], previous, payload) if hashlib.sha256(content).hexdigest() != entry['sha256']: raise ValueError(f'restored_resource_hash_mismatch:{name}') destination = target/relative destination.parent.mkdir(parents=True, exist_ok=True) if destination.name.endswith('.safetensors.zst'): content = zstd.compress(content, level=9) with destination.open('xb') as stream: stream.write(content) finally: resources.temporary.cleanup()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""文字ラベルの経路と、原文から推定した項目数で抽出候補を比較する。"""from collections import Counter
import numpy as npimport torch
from shared.bibform_trial import FIELDSfrom shared.span_tagger import (OUTER_NAMES,joint_constraint_tables, prediction_from_labels,viterbi_paths)
def count_vector(prediction): counts=Counter(field['label'] for field in prediction['fields']) return np.array([min(counts[label],3) for label in FIELDS],np.int64)
def count_direction(log_probabilities,counts): target=log_probabilities.argmax(-1) current=log_probabilities[np.arange(len(FIELDS)),counts] preferred=log_probabilities[np.arange(len(FIELDS)),target] difference=target-counts return np.sign(difference)*np.minimum((preferred-current)/np.maximum(np.abs(difference),1),10.)
def decode_candidates(head,outer,names,lengths,inputs,begin_bias=None): states,legal,initial,final=joint_constraint_tables() outer_ids=torch.tensor([s[0] for s in states],device=outer.device) name_ids=torch.tensor([s[1] for s in states],device=outer.device) work=outer.float().clone();location=OUTER_NAMES.index('LOCATION') work[:,:,1+2*location:3+2*location]=-10000 original=(work[...,outer_ids]+names.float()[...,name_ids]).cpu() if begin_bias is not None: starts=torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS],device=outer.device) work[:,:,starts]+=begin_bias[:,None,:] emissions=(work[...,outer_ids]+names.float()[...,name_ids]).cpu() transition=head.outer_transitions[outer_ids[:,None],outer_ids[None,:]]+head.names_transitions[name_ids[:,None],name_ids[None,:]] start=head.outer_start[outer_ids]+head.names_start[name_ids] end=head.outer_end[outer_ids]+head.names_end[name_ids] transition=legal+head.transition_scale*transition.cpu() start=initial+head.transition_scale*start.cpu();end=final+head.transition_scale*end.cpu() paths=viterbi_paths(emissions,[int(n) for n in lengths],transition,start,end) predictions=[];scores=[] for i,(row,path) in enumerate(zip(inputs,paths,strict=True)): predictions.append(prediction_from_labels(row['id'],row['text'],[states[s][0] for s in path],[states[s][1] for s in path])) selected=torch.tensor(path,dtype=torch.long) score=original[i,torch.arange(len(path)),selected].double().sum() score+=transition[selected[:-1],selected[1:]].double().sum()+start[selected[0]].double()+end[selected[-1]].double() scores.append(float(score)) return predictions,np.array(scores,np.float64)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""文字経路の得点を保ち、学習した項目数で原文だけの抽出候補を選ぶ。"""from copy import deepcopy
import numpy as npimport torch
from shared.bibform_trial import FIELDS,signaturefrom shared.count_guided_candidates import count_direction,count_vector,decode_candidatesfrom shared.span_tagger import OUTER_NAMESfrom shared.global_field_counts import field_start_mass
class CountGuidedPredictor: def __init__(self,model,generation_scales,ranking_scale,minimum_gain=.1): assert generation_scales and all(np.isfinite(v) and 0<v<=4 for v in generation_scales) assert np.isfinite(ranking_scale) and ranking_scale>=0 and np.isfinite(minimum_gain) and minimum_gain>=0 self.model=model.eval();self.generation_scales=tuple(generation_scales) self.ranking_scale=ranking_scale;self.minimum_gain=minimum_gain self.capture_logits = False self.title_residual = None self.title_residual_scale = 0.
@torch.inference_mode() def predict(self,head,features,lengths,inputs,role_threshold,postprocess): assert head.hidden_width==192 and head.label_transitions and head.structure=='unrestricted' if head.field_presence_prior: hidden,presence=head.encode(features,lengths,inputs,return_presence=True) else:hidden=head.encode(features,lengths,inputs) outer,names=head.outer(hidden),head.names(hidden) soft_mass=field_start_mass(outer,lengths) if self.model.use_soft_mass else None if head.field_presence_prior: prior=head.field_presence_prior odds=torch.tensor(prior['log_prior_odds'],device=outer.device) eligible=torch.tensor(prior['eligible'],device=outer.device) evidence=(presence[:,:len(FIELDS)]-head.presence_positive_weights[:len(FIELDS)].log()-odds).clamp(-10,10)*eligible starts=torch.tensor([1+2*OUTER_NAMES.index(label) for label in FIELDS],device=outer.device) outer[:,:,starts]+=prior['scale']*evidence[:,None,:] if self.title_residual is not None and self.title_residual_scale: outer = self.title_residual.adjust(outer,hidden,lengths,self.title_residual_scale) return self.predict_from_scores(head,hidden,outer,names,lengths,inputs,role_threshold,postprocess,soft_mass)
@torch.inference_mode() def predict_from_scores(self,head,hidden,outer,names,lengths,inputs,role_threshold,postprocess,soft_mass): valid=(torch.arange(hidden.shape[1],device=hidden.device)[None,:]<lengths[:,None])[...,None] global_features=torch.cat([(hidden*valid).sum(1)/lengths[:,None],hidden.masked_fill(~valid,-torch.inf).amax(1)],-1) logp=self.model(global_features,soft_mass).log_softmax(-1).cpu().numpy() self.last_count_logp=logp self.last_global_features=global_features.cpu().numpy() self.last_hidden=hidden.detach() if self.capture_logits: self.last_logits = (outer.detach(), names.detach())
def finish(rows,raw,values,sizes): mentions=[(i,p['start'],p['end']) for i,row in enumerate(raw) for p in row['contributors']] assigned=head.assign_roles(rows,raw,head.role_scores(values,sizes,mentions),role_threshold) return [postprocess(inp['text'],row) for inp,row in zip(rows,assigned,strict=True)]
raw,local=decode_candidates(head,outer,names,lengths,inputs) baseline=finish(inputs,raw,hidden,lengths) counts=np.stack([count_vector(row) for row in baseline]) directions=np.stack([count_direction(lp,number) for lp,number in zip(logp,counts,strict=True)]) selected=list(baseline) known=[{signature(row)} for row in baseline] base_global=np.array([lp[np.arange(len(FIELDS)),number].sum() for lp,number in zip(logp,counts,strict=True)]) best=local+self.ranking_scale*base_global;original=best.copy() affected=np.flatnonzero(np.any(directions!=0,axis=1)) if not len(affected) or not self.ranking_scale:return selected index=torch.tensor(affected,device=hidden.device);rows=[inputs[i] for i in affected] for scale in self.generation_scales: bias=torch.from_numpy((scale*directions[affected]).astype(np.float32)).to(hidden.device) raw,scores=decode_candidates(head,outer[index],names[index],lengths[index],rows,bias) candidates=finish(rows,raw,hidden[index],lengths[index]) for parent,row,score in zip(affected,candidates,scores,strict=True): value=signature(row) if value in known[parent]:continue known[parent].add(value) number=count_vector(row);global_score=float(logp[parent,np.arange(len(FIELDS)),number].sum()) total=score+self.ranking_scale*global_score if total>best[parent] and total-original[parent]>self.minimum_gain: best[parent]=total;selected[parent]=row return selected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""CSLが出力した注釈から、表示された項目・人物・姓名の文字範囲を構成する。"""
from html.parser import HTMLParserfrom difflib import SequenceMatcherimport hashlibimport randomimport re
from shared.dataset_schema import RAW_FIELD_NAMES as FIELD_NAMES, stable_seedfrom shared.text_offsets import transform_characters
class AnnotatedHTML(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.text = "" self.stack: list[tuple[str, int]] = [] self.annotations: list[tuple[str, int, int]] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: if tag == "mark": self.stack.append((dict(attrs)["data-label"], len(self.text)))
def handle_endtag(self, tag: str) -> None: if tag == "mark": label, start = self.stack.pop() self.annotations.append((label, start, len(self.text)))
def handle_data(self, text: str) -> None: self.text += text
def parse_rendered(html: str) -> tuple[str, list[tuple[str, int, int]]]: parser = AnnotatedHTML() parser.feed(html) replacements = [] previous_space = True for char in parser.text: space = char.isspace() replacements.append("" if space and previous_space else " " if space else char) previous_space = space text, spans = transform_characters(parser.text, parser.annotations, replacements) text = text.rstrip() trimmed = [] for label,start,end in spans: end = min(end,len(text)) while start<end and text[start].isspace(): start+=1 while end>start and text[end-1].isspace(): end-=1 if end>start: trimmed.append((label,start,end)) return text, trimmed
def canonical_annotations(html: str, plain_html: str) -> tuple[str,list[tuple[str,int,int]]]: text, annotations = parse_rendered(html) plain,_ = parse_rendered(plain_html) if text==plain: return text,annotations if re.sub(r"[\W_]","",text)!=re.sub(r"[\W_]","",plain): raise ValueError("annotation_changed_bibliographic_content") starts=[0]*(len(text)+1);ends=[0]*(len(text)+1);inserts=[] for operation,i,j,a,b in SequenceMatcher(None,text,plain,autojunk=False).get_opcodes(): if operation=="insert": inserts.append((i,a,b));continue for index in range(i,j+1): value=a+(index-i) if operation=="equal" else a+round((index-i)*(b-a)/max(j-i,1)) starts[index]=ends[index]=value for index,a,b in inserts: starts[index]=b;ends[index]=a return plain,[(label,starts[left],ends[right]) for label,left,right in annotations if starts[left]<ends[right]]
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]: text, annotations = canonical_annotations(html,plain_html) if plain_html is not None else parse_rendered(html) if noisy: rng = random.Random(stable_seed(record["source_id"]+style+str(variant), 20261110)) table = {",":",", ";":";", ":":":", "(":"(", ")":")", "[":"[", "]":"]"} fullwidth = rng.random()<.65 replacements = [] for i,char in enumerate(text): value = table.get(char,char) if fullwidth else char if char==" " and i>30 and rng.random()<.10: value="\n" if char in {"–","—"} and rng.random()<.5: value="-" if char==" " and i>0 and text[i-1]=="." and rng.random()<.20: value="" replacements.append(value) text, annotations = transform_characters(text, annotations, replacements) roles={p["role"].upper() for p in record.get("people",[])} role_labels={"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"} 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])) # 日付の書式が年月日を表示しても、既存のYEAR層は表示された年だけを対象にする。 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) for label,start,end in fields] selected = [] for field in fields: if selected and field[1]<selected[-1][2]: if field[2]<=selected[-1][2]: continue raise ValueError("overlapping_csl_fields") selected.append(field) people = [] for label,start,end in sorted(annotations,key=lambda s:s[1]): if label not in {"PERSON","ORGANIZATION"}: continue parents = [f for f in selected if f[0] in {"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"} and f[1]<=start<end<=f[2]] if len(parents)!=1: raise ValueError("person_without_unique_role") person = {"kind":label,"start":start,"end":end,"role":parents[0][0].lower(),"order":len(people)} for part,left,right in annotations: if part in {"FAMILY","GIVEN"} and start<=left<right<=end: if part.lower() in person: raise ValueError("fragmented_name_part") person[part.lower()]={"start":left,"end":right} people.append(person) omissions=[] for role in {p["role"] for p in record.get("people",[])}: total=sum(p["role"]==role for p in record["people"]) shown=sum(p["role"]==role for p in people) if shown<total: omissions.append({"role":role,"source_count":total,"visible_count":shown}) spans = [{"label":label,"start":start,"end":end,"text":text[start:end], "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] return {"id":hashlib.sha256(f"csl-v2:{record['source_id']}:{split}:{style}:{variant}".encode()).hexdigest()[:24], "base_id":record["source_id"],"group_id":group_id,"split":split,"style":style, "language":record["language"],"kind":record["kind"],"text":text,"spans":spans,"people":people, "omissions":omissions,"source":record["source"],"source_url":record["source_url"],"metadata_terms":record["metadata_terms"],"noisy":noisy}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""v1を保存したまま、出典付きの書誌修正と区切り空白の学習例を作る。"""
from copy import deepcopyimport re
from shared.dataset_schema import validate_target, visible_valuefrom shared.text_offsets import transform_characters
# 小文字の独立語だけを移す。Van という名や Binard-van のような複合名は推定しない。PARTICLE = re.compile(r'^(.*?)\s+((?:van (?:der|den|de)|de (?:la|los|las)|von der|van|von|de|del|der|den|da|di|du))$')LIFESPAN = re.compile(r',\s*(?:[12]\d{3})?\s*[-–—]\s*(?:[12]\d{3})?\s*$')
def revise_record(record: dict, reviewed: list[dict]) -> tuple[dict, list[dict]]: result = deepcopy(record) changes = [] for correction in reviewed: if correction['source_id'] != record['source_id']: continue current = result for key in correction['path'][:-1]: current = current[key] key = correction['path'][-1] if correction.get('operation') == 'add': if key in current: raise ValueError('reviewed_correction_target_exists:' + record['source_id']) if correction['before'] is not None: raise ValueError('reviewed_addition_requires_missing_before:' + record['source_id']) elif current[key] != correction['before']: raise ValueError('reviewed_correction_before_changed:' + record['source_id']) current[key] = correction['after'] changes.append(correction) for index, person in enumerate(result['people']): if person['literal']: continue for part in ('family', 'given'): before = person[part] after = LIFESPAN.sub('', before).strip() if after != before and after and re.search(r'\d{4}', before): person[part] = after changes.append({'source_id':record['source_id'], 'path':['people',index,part], 'before':before, 'after':after, 'reason':'氏名末尾に混入した生没年を除去'}) match = PARTICLE.fullmatch(person['given']) if match and match[1] and person['family']: before = {'family':person['family'], 'given':person['given']} person['given'] = match[1] person['family'] = match[2] + ' ' + person['family'] changes.append({'source_id':record['source_id'], 'path':['people',index], 'before':before, 'after':{'family':person['family'], 'given':person['given']}, 'reason':'独立した小文字の姓の前置詞をfamilyへ統一するv2の姓名方針'}) if re.match(r'^故\s+', person['family']): before = person['family'] person['family'] = re.sub(r'^故\s+', '', before) changes.append({'source_id':record['source_id'], 'path':['people',index,'family'], 'before':before, 'after':person['family'], 'reason':'姓に混入した故人の接頭辞を除去'}) return result, changes
def separator_spacing(text: str, target: dict, new_id: str, variant: int = 0) -> tuple[str, dict]: """項目の外の区切りだけへ空白を挿入し、内容と正解の境界を保つ。""" spans = [('field:' + str(i), span['start'], span['end']) for i, span in enumerate(target['fields'])] for i, person in enumerate(target['contributors']): spans.append((f'person:{i}', person['start'], person['end'])) spans.extend((f'{part}:{i}', span['start'], span['end']) for part, span in person['name_parts'].items()) occupied = [False] * len(text) for _, start, end in spans: occupied[start:end] = [True] * (end-start) replacements = [('\n' if variant == 1 else ' ') + char if char in ':;:;' and not occupied[i] else char for i,char in enumerate(text)] changed, moved = transform_characters(text, spans, replacements) result = deepcopy(target) result['id'] = new_id for label,start,end in moved: kind, index = label.split(':') item = (result['fields'][int(index)] if kind == 'field' else result['contributors'][int(index)] if kind == 'person' else result['contributors'][int(index)]['name_parts'][kind]) item.update(start=start, end=end, value=visible_value(changed[start:end], item.get('label', kind))) validate_target(changed, result) return changed, result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""引用文字列から見える情報と、収集メタデータを分離するデータ仕様。"""
import hashlibfrom copy import deepcopyimport randomimport reimport unicodedata
from shared.text_offsets import transform_characters
RAW_FIELD_NAMES=("AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR","TITLE","JOURNAL","BOOKTITLE","YEAR","DATE","VOLUME","ISSUE","PAGES","PUBLISHER","LOCATION","DOI","ISBN","URL","EDITION","VERSION","INSTITUTION")FIELD_NAMES=("TITLE","CONTAINER_TITLE","DATE","VOLUME","ISSUE","PAGES","ISSUER","LOCATION","DOI","ISBN","URL","EDITION","VERSION")FIELD_MAP={**{name:name for name in FIELD_NAMES},"YEAR":"DATE","JOURNAL":"CONTAINER_TITLE","BOOKTITLE":"CONTAINER_TITLE","PUBLISHER":"ISSUER","INSTITUTION":"ISSUER"}SCHEMA_VERSION="bibliography-visible-spans/1"
def stable_seed(value: str, seed: int = 20261110) -> int: return int(hashlib.sha256(f"{seed}:{value}".encode()).hexdigest()[:16],16)
def visible_value(text: str,label: str) -> str: value=" ".join(text.split()) return unicodedata.normalize("NFKC",value) if label in {"DOI","URL","ISBN"} else value
def primary_target(sample: dict[str,object]) -> dict[str,object]: text=sample["text"];fields=[];contributors=[] for span in sample["spans"]: if span["label"] in {"AUTHOR","EDITOR","BOOKEDITOR","TRANSLATOR"}:continue label=FIELD_MAP[span["label"]];start,end=span["start"],span["end"] fields.append({"label":label,"start":start,"end":end,"value":visible_value(text[start:end],label)}) for person in sample["people"]: row={"kind":person["kind"].lower(),"start":person["start"],"end":person["end"],"value":visible_value(text[person["start"]:person["end"]],"CONTRIBUTOR"),"name_parts":{}} for part in ("family","given"): if part in person: start,end=person[part]["start"],person[part]["end"] row["name_parts"][part]={"start":start,"end":end,"value":visible_value(text[start:end],part)} contributors.append(row) result={"id":sample["id"],"fields":fields,"contributors":contributors} validate_target(text,result) return result
def validate_target(text: str,target: dict[str,object]) -> None: previous=0 for field in target["fields"]: if set(field)!={"label","start","end","value"}:raise ValueError("invalid_field_keys") if field["label"] not in FIELD_NAMES:raise ValueError("unknown_target_field") a,b=field["start"],field["end"] if type(a) is not int or type(b) is not int:raise ValueError("offset_must_be_integer") if not previous<=a<b<=len(text):raise ValueError("invalid_or_overlapping_target_field") previous=b if field["value"]!=visible_value(text[a:b],field["label"]):raise ValueError("target_value_not_grounded_in_input") previous=0 for person in target["contributors"]: if set(person)!={"kind","start","end","value","name_parts"}:raise ValueError("invalid_contributor_keys") a,b=person["start"],person["end"] if type(a) is not int or type(b) is not int:raise ValueError("offset_must_be_integer") if person["kind"] not in {"person","organization"} or not previous<=a<b<=len(text):raise ValueError("invalid_or_overlapping_contributor") previous=b if any(f["start"]<b and f["end"]>a for f in target["fields"]):raise ValueError("contributor_overlaps_bibliographic_field") if person["value"]!=visible_value(text[a:b],"CONTRIBUTOR"):raise ValueError("contributor_value_not_grounded") if (person["kind"]=="organization")!= (not person["name_parts"]):raise ValueError("contributor_kind_name_parts_disagree") covered=[] for part,span in person["name_parts"].items(): 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") if part not in {"family","given"} or not a<=span["start"]<span["end"]<=b:raise ValueError("invalid_name_part") if any(start<span["end"] and end>span["start"] for start,end in covered):raise ValueError("overlapping_name_parts") covered.append((span["start"],span["end"])) if span["value"]!=visible_value(text[span["start"]:span["end"]],part):raise ValueError("name_value_not_grounded") if set(target)!={"id","fields","contributors"}:raise ValueError("hidden_metadata_in_primary_target")
def target_signature(target: dict[str,object]) -> tuple[object,...]: fields=tuple(sorted((f["label"],f["start"],f["end"]) for f in target["fields"])) 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"])) return fields,people
def require_identifying_content(target: dict[str,object]) -> None: labels={f["label"] for f in target["fields"]} if not (labels&{"TITLE","DOI","ISBN","URL"} or ("CONTAINER_TITLE" in labels and labels&{"VOLUME","PAGES"})): raise ValueError("citation_without_title_identifier_or_container_locator")
def script_profile(text: str) -> dict[str,int]: 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)}
def bio_labels(length: int,spans: list[tuple[str,int,int]],names: tuple[str,...]) -> list[int]: result=[0]*length for label,start,end in spans: if label not in names or not 0<=start<end<=length or any(result[start:end]):raise ValueError("invalid_or_overlapping_bio_span") index=1+2*names.index(label);result[start]=index for position in range(start+1,end):result[position]=index+1 return result
def formatting_noise(text: str,target: dict[str,object],seed: int,new_id: str) -> tuple[str,dict[str,object]]: rng=random.Random(seed);replacements=[];fullwidth={",":",",":":":",";":";","(":"(",")":")"} for char in text: value=char if char==" ": number=rng.random() if number<.07:value="\n" elif number<.10:value=" " elif char in fullwidth and rng.random()<.30:value=fullwidth[char] elif char in "–—" and rng.random()<.5:value="-" replacements.append(value) if "".join(replacements)==text: position=next((i for i,c in enumerate(text) if c==" "),None) if position is not None:replacements[position]="\n" annotations=[("field:"+str(i),s["start"],s["end"]) for i,s in enumerate(target["fields"])] for index,person in enumerate(target["contributors"]): annotations.append((f"person:{index}",person["start"],person["end"])) for part,span in person["name_parts"].items():annotations.append((f"{part}:{index}",span["start"],span["end"])) changed,spans=transform_characters(text,annotations,replacements);result=deepcopy(target);result["id"]=new_id for label,start,end in spans: kind,index=label.split(":");index=int(index) item=result["fields"][index] if kind=="field" else result["contributors"][index] if kind=="person" else result["contributors"][index]["name_parts"][kind] item.update(start=start,end=end) value_label=item["label"] if kind=="field" else kind item["value"]=visible_value(changed[start:end],value_label) def content(value: str) -> str:return "".join(unicodedata.normalize("NFKC",value).translate(str.maketrans({"–":"-","—":"-"})).split()) if content(changed)!=content(text):raise ValueError("noise_changed_bibliographic_content") validate_target(changed,result) return changed,result12345678910111213141516171819202122232425262728293031323334353637"""認識済みの日付へ隣接する説明語を、他の抽出範囲に重ならない場合だけ含める。"""
from copy import deepcopyfrom functools import lru_cacheimport re
from shared.dataset_schema import visible_value
@lru_cache(maxsize=16)def qualifier_pattern(phrases: tuple[str, ...]) -> re.Pattern: alternatives = [r'\s+'.join(re.escape(word) for word in phrase.split()) for phrase in sorted(phrases, key=len, reverse=True)] return re.compile(r'(?<![A-Za-z])(?:' + '|'.join(alternatives) + r')\s*', re.I)
def extend_date_qualifiers(text: str, prediction: dict, phrases: list[str]) -> dict: result = deepcopy(prediction) if not phrases: return result pattern = qualifier_pattern(tuple(phrases)) for index, field in enumerate(result['fields']): if field['label'] != 'DATE': continue start, end = field['start'], field['end'] offset = max(0, start - 64) window = text[offset:min(end, start + 64)] candidates = [offset + match.start() for match in pattern.finditer(window) if offset + match.start() < start <= offset + match.end() < end] if not candidates: continue revised = min(candidates) protected = [f for i, f in enumerate(result['fields']) if i != index] + result['contributors'] if any(revised < span['end'] and span['start'] < start for span in protected): continue field.update(start=revised, value=visible_value(text[revised:end], 'DATE')) return result1234567891011121314151617181920212223242526272829303132333435363738394041424344"""訓練書誌で確認したDOIの数値構造から、既知の巻と異なる年の誤分類を補助する。"""
from copy import deepcopyimport re
def doi_numbers(value: str) -> tuple[str, str, list[re.Match]] | None: match = re.fullmatch(r'(10\.\d{4,9})/(.+)', value.casefold()) if match is None: return None suffix = match[2] numbers = list(re.finditer(r'\d+', suffix)) if not numbers: return None # 数字の前後の記号まで一致する系列だけをまとめる。 key = match[1] + '/' + re.sub(r'\d+', '#', suffix) return key, suffix, numbers
def inferred_volume(doi: str, rules: dict) -> str | None: parts = doi_numbers(doi) if parts is None: return None key, suffix, numbers = parts rule = rules.get(key) if rule is None: return None value = suffix[numbers[rule['begin']].start():numbers[rule['end']].end()] return value if value in rule['observed_volumes'] else None
def apply_doi_volume_prior(prediction: dict, rules: dict) -> dict: result = deepcopy(prediction) volumes = {value for field in prediction['fields'] if field['label'] == 'DOI' if (value := inferred_volume(field['value'], rules)) is not None} if len(volumes) != 1: return result volume = next(iter(volumes)) years = {match[0] for field in prediction['fields'] if field['label'] == 'DATE' for match in re.finditer(r'(?<!\d)(?:1[5-9]|20)\d{2}(?!\d)', field['value'])} for field in result['fields']: if field['label'] == 'VOLUME' and field['value'] in years and field['value'] != volume: field['label'] = 'DATE' return result123456789101112131415161718192021"""同一項目の隣接した断片だけを、固定した接続条件で合わせる。"""from copy import deepcopyimport refrom shared.dataset_schema import visible_value
def merge_field_fragments(text: str, prediction: dict, rules: list[dict]) -> dict: result = deepcopy(prediction) merged = [] for field in result['fields']: previous = merged[-1] if merged else None if previous and previous['label'] == field['label']: gap = text[previous['end']:field['start']] applicable = any(rule['label'] == field['label'] and re.fullmatch(rule['gap_pattern'], gap) for rule in rules) protected = any(previous['end'] < p['end'] and p['start'] < field['start'] for p in result['contributors']) if applicable and not protected: previous.update(end=field['end'], value=visible_value(text[previous['start']:field['end']], field['label'])) continue merged.append(field) result['fields'] = merged return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""固定した3補助モデルの文字表現から、候補範囲の項目種別と不採用を判定する。"""from collections import Counterfrom copy import deepcopy
import numpy as npimport torchfrom torch import nn
from shared.bibform_trial import FIELDS,validatefrom shared.dataset_schema import visible_value
DESCRIPTOR_WIDTH=4*576+3
def span_descriptors(characters:np.ndarray,spans:list[tuple[int,int]],character_width:int=576) -> np.ndarray: assert character_width in (192,576) values=np.asarray(characters[:,:192] if character_width==192 else characters[:,192:768],dtype=np.float32) assert values.ndim==2 and values.shape[1]==character_width and len(values)>0 bounds=np.asarray(spans,dtype=np.int64).reshape(-1,2) assert np.all(bounds[:,0]>=0) and np.all(bounds[:,1]<=len(values)) and np.all(bounds[:,1]>bounds[:,0]) prefix=np.concatenate([np.zeros((1,character_width),dtype=np.float32),values.cumsum(0,dtype=np.float32)]) start,end=bounds[:,0],bounds[:,1] length=end-start geometry=np.stack([start/len(values),end/len(values),np.log1p(length)/np.log1p(len(values))],-1).astype(np.float32)*4 return np.concatenate([values[start],values[end-1],(prefix[end]-prefix[start])/length[:,None], np.broadcast_to(values.mean(0),(len(spans),character_width)),geometry],-1).astype(np.float16)
class FieldSpanClassifier(nn.Module): def __init__(self,width:int=64,neural_context_width:int=0,character_width:int=576): super().__init__() assert neural_context_width in (0,384) self.neural_context_width=neural_context_width assert character_width in (192,576) self.character_width=character_width input_width=4*character_width+3+neural_context_width self.network=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,width), nn.GELU(),nn.Dropout(.1),nn.Linear(width,len(FIELDS)+1))
def forward(self,descriptors:torch.Tensor) -> torch.Tensor: return self.network(descriptors)
def append_neural_context(descriptors:np.ndarray,context:np.ndarray) -> np.ndarray: assert descriptors.ndim==2 and descriptors.shape[1] in (DESCRIPTOR_WIDTH,771) and context.shape==(384,) return np.concatenate([descriptors,np.broadcast_to(context.astype(np.float16),(len(descriptors),384))],-1).astype(np.float16)
def overlaps(left:tuple[int,int],right:tuple[int,int]) -> bool: return left[0]<right[1] and right[0]<left[1]
def candidate_spans(text:str,baseline:dict,index:int) -> list[tuple[int,int]]: field=baseline['fields'][index];start,end=field['start'],field['end'] variants={(start,end)} variants.update((start+delta,end) for delta in (-4,-3,-2,-1,1,2,3,4)) variants.update((start,end+delta) for delta in (-4,-3,-2,-1,1,2,3,4)) variants.update((start+delta,end+delta) for delta in (-4,-2,-1,1,2,4)) blockers=[(f['start'],f['end']) for i,f in enumerate(baseline['fields']) if i!=index] blockers.extend((p['start'],p['end']) for p in baseline['contributors']) return sorted(span for span in variants if 0<=span[0]<span[1]<=len(text) and not text[span[0]].isspace() and not text[span[1]-1].isspace() and not any(overlaps(span,other) for other in blockers))
def apply_proposals(text:str,original:dict,proposals:list,minimum_gain:float, count_logp:np.ndarray|None=None,count_scale:float=0.) -> dict: row=deepcopy(original);changed=set() for gain,index,label,start,end in sorted(proposals,reverse=True): if gain<=minimum_gain:break if index in changed:continue if count_logp is not None and count_scale: counts=Counter(field['label'] for field in row['fields']) before=np.array([min(counts[field],3) for field in FIELDS]) counts[row['fields'][index]['label']]-=1;counts[label]+=1 after=np.array([min(counts[field],3) for field in FIELDS]) count_gain=float((count_logp[np.arange(len(FIELDS)),after]-count_logp[np.arange(len(FIELDS)),before]).sum()) if gain+min(0.,count_scale*count_gain)<=minimum_gain:continue blocked=any(overlaps((start,end),(f['start'],f['end'])) for i,f in enumerate(row['fields']) if i!=index) if blocked:continue row['fields'][index]={'label':label,'start':start,'end':end,'value':visible_value(text[start:end],label)};changed.add(index) row['fields'].sort(key=lambda f:(f['start'],f['end'],f['label'])) return row
class FieldSpanRefiner: def __init__(self,model:FieldSpanClassifier,minimum_gain:float,count_scale:float=0.,boundary_only:bool=False): assert np.isfinite(minimum_gain) and minimum_gain>=0 and np.isfinite(count_scale) and count_scale>=0 self.model=model.cpu().eval();self.minimum_gain=minimum_gain self.count_scale=count_scale;self.boundary_only=boundary_only
@torch.inference_mode() def proposals(self,characters:np.ndarray,inp:dict,original:dict,neural_context:np.ndarray|None=None) -> list: options=[candidate_spans(inp['text'],original,i) for i in range(len(original['fields']))] spans=sorted({span for candidates in options for span in candidates}) if not spans:return [] positions={span:i for i,span in enumerate(spans)} descriptors=span_descriptors(characters,spans,self.model.character_width) if self.model.neural_context_width: assert neural_context is not None descriptors=append_neural_context(descriptors,neural_context) logp=self.model(torch.from_numpy(descriptors.astype(np.float32))).log_softmax(-1).numpy() proposals=[] for index,(field,candidates) in enumerate(zip(original['fields'],options,strict=True)): old=(field['start'],field['end']);old_label=1+FIELDS.index(field['label']) before=logp[positions[old],old_label] for start,end in candidates: for label_index,label in enumerate(FIELDS,1): if self.boundary_only and label!=field['label']:continue movement=abs(start-old[0])+abs(end-old[1]) gain=float(logp[positions[start,end],label_index]-before)-.1*movement-.25*(label!=field['label']) if gain>.25:proposals.append((gain,index,label,start,end)) return proposals
@torch.inference_mode() def predict(self,features:torch.Tensor,inputs:list[dict],predictions:list[dict],count_logp:np.ndarray|None=None, neural_context:np.ndarray|None=None) -> list[dict]: characters=features[:,:,:768].detach().cpu().numpy() assert not self.count_scale or count_logp is not None assert not self.model.neural_context_width or neural_context is not None result=[] for row_index,(inp,original) in enumerate(zip(inputs,predictions,strict=True)): assert inp['id']==original['id'] proposals=self.proposals(characters[row_index,:len(inp['text'])],inp,original, neural_context[row_index] if neural_context is not None else None) revised=apply_proposals(inp['text'],original,proposals,self.minimum_gain, count_logp[row_index] if count_logp is not None else None,self.count_scale) validate(inp['text'],revised);result.append(revised) return result
12345678910111213141516171819202122232425262728293031323334353637383940"""保存した抽出器の文字表現を取得し、範囲予測層へ渡す。原文だけを入力する。"""import jsonfrom pathlib import Path
from safetensors.torch import load_fileimport torch
from shared.range_extraction import build_range_head,prediction_from_rangesfrom shared.span_tagger import EncodedCitation,load_package
class RangePredictor: def __init__(self,package: Path,device: str) -> None: self.device=device self.model,self.tokenizer,self.config=load_package(package,device) self.range_config=json.loads((package/'range_model.json').read_text()) self.head=build_range_head(self.range_config['architecture'],192*len(self.model.members)).to(device) self.head.load_state_dict(load_file(package/'range_head.safetensors',device=device));self.head.eval() self.features={};self.handles=[] for index,member in enumerate(self.model.members): def capture(module: object,args: tuple,i: int=index) -> None:self.features[i]=args[0].detach() self.handles.append(member.heads[0].register_forward_pre_hook(capture))
@torch.inference_mode() def predict(self,inputs: list[dict],batch_size: int=16) -> list[dict]: 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') if len({r['id'] for r in inputs})!=len(inputs):raise ValueError('duplicate_input_id') ordered=sorted(inputs,key=lambda row:len(row['text']));predictions={} for begin in range(0,len(ordered),batch_size): chunk=ordered[begin:begin+batch_size] rows=[EncodedCitation(r['id'],r['text'],[0],[],[],[],None) for r in chunk] self.model.member_text_outputs(rows,self.device) # キャッシュ学習と実行時で、文字表現の保存精度を同じにする。 maximum=max(len(r['text']) for r in chunk) features=torch.cat([self.features[i][:,:maximum] for i in range(len(self.model.members))],dim=-1).half().float() lengths=torch.tensor([len(r['text']) for r in chunk],device=self.device) options={'texts':[r['text'] for r in chunk]} if getattr(self.head,'needs_text',False) else {} ranges=self.head.extract(features,lengths,float(self.range_config['threshold']),**options) for row,spans in zip(chunk,ranges,strict=True):predictions[row['id']]=prediction_from_ranges(row['id'],row['text'],spans) return [predictions[r['id']] for r in inputs]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""原文から得た引用全体の表現で、表示項目の個数を予測する。"""import torchfrom torch import nn
from shared.bibform_trial import FIELDSfrom shared.span_tagger import OUTER_NAMES
def field_start_mass(outer, lengths): """項目開始の確率を原文の有効文字だけで合計する。""" logits=outer.float().clone() location=OUTER_NAMES.index('LOCATION') logits[...,1+2*location:3+2*location]=-10000 starts=[1+2*OUTER_NAMES.index(label) for label in FIELDS] valid=torch.arange(outer.shape[1],device=outer.device)[None,:]<lengths[:,None] return (logits.softmax(-1)[...,starts]*valid[...,None]).sum(1).log1p()
class GlobalFieldCounts(nn.Module): def __init__(self, use_soft_mass=False): super().__init__() self.use_soft_mass=use_soft_mass self.network=nn.Sequential(nn.LayerNorm(384),nn.Linear(384,128),nn.GELU(), nn.Dropout(.1),nn.Linear(128,len(FIELDS)*4)) if use_soft_mass: self.mass_residual=nn.Sequential(nn.Linear(len(FIELDS),32),nn.GELU(),nn.Linear(32,len(FIELDS)*4)) nn.init.zeros_(self.mass_residual[-1].weight) nn.init.zeros_(self.mass_residual[-1].bias)
def forward(self,features,soft_mass=None): logits=self.network(features) if self.use_soft_mass: if soft_mass is None:raise ValueError('field_start_mass_required') logits=logits+self.mass_residual(soft_mass) return logits.reshape(-1,len(FIELDS),4)
@torch.no_grad() def initialize(self,source,frequencies,warm): if warm: for index in (0,1):self.network[index].load_state_dict(source.global_presence_head[index].state_dict()) previous=source.global_presence_head[3] self.network[4].weight.zero_();self.network[4].bias.zero_() conditional=(frequencies[:,1:]+.5)/(frequencies[:,1:].sum(-1,keepdim=True)+1.5) for label in range(len(FIELDS)): for count in range(1,4): self.network[4].weight[label*4+count]=previous.weight[label] self.network[4].bias[label*4+count]=(previous.bias[label] -source.presence_positive_weights[label].log()+conditional[label,count-1].log()) else: self.network[4].weight.zero_() self.network[4].bias.copy_(((frequencies+.5)/(frequencies.sum(-1,keepdim=True)+2)).log().flatten())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""原文に対する固定抽出器の得点を、辞書を使わずに統合する。"""from copy import deepcopy
import torchfrom torch import Tensor
def combine_scores(outputs: list[list[Tensor]], weights: Tensor, settings: dict) -> list[Tensor]: from shared.span_tagger import combine_ensemble_logits mode = settings.get('fusion', 'logits') if mode == 'logits': return combine_ensemble_logits(outputs, weights) normalized = weights / weights.sum(1, keepdim=True) result = [] temperature = float(settings.get('temperature', 1.)) if temperature <= 0: raise ValueError('positive_fusion_temperature_required') for head in range(2): scores = [values[head].float() for values in outputs] own_weights = [normalized[head, i] if normalized.ndim == 2 else normalized[head, i, :, None, None] for i in range(len(scores))] if mode == 'probabilities': values = [(value / temperature).softmax(-1) for value in scores] merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)).clamp_min(1e-12).log() # 温度を変える比較でも、姓名得点との相対尺度は元へ戻す。 merged = merged * temperature elif mode == 'standardized_logits': values = [(value - value.mean(-1, keepdim=True)) / value.std(-1, keepdim=True, correction=0).clamp_min(.1) for value in scores] reference = sum(value.std(-1, keepdim=True, correction=0) * weight for value, weight in zip(scores, own_weights, strict=True)).clamp_min(.1) merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)) * reference elif mode == 'votes': values = [torch.nn.functional.one_hot(value.argmax(-1), value.shape[-1]).float() for value in scores] merged = sum(value * weight for value, weight in zip(values, own_weights, strict=True)) * float(settings.get('vote_scale', 8.)) elif mode == 'median_logits': values = [value - value.mean(-1, keepdim=True) for value in scores] merged = torch.stack(values).median(0).values else: raise ValueError('unknown_score_fusion:' + mode) result.append(merged) if settings.get('scope', 'outer') == 'outer': result[1] = combine_ensemble_logits(outputs, weights)[1] return result
def structural_predictions(logits: list[Tensor], rows: list, name_weight: float, settings: dict) -> list[dict]: from shared.span_tagger import OUTER_NAMES, decode_predictions, joint_constraint_tables, prediction_from_labels, viterbi_paths base = decode_predictions(logits, rows, 'joint', name_weight) constraint = settings.get('structure') if not constraint: return base if constraint != 'single_title': raise ValueError('unknown_structure_constraint') title_begin = 1 + 2 * OUTER_NAMES.index('TITLE') title_inside = title_begin + 1 # 既に条件を満たす引用の解は、探索空間を狭めても変わらない。 selected = [i for i, pred in enumerate(base) if sum(f['label'] == 'TITLE' for f in pred['fields']) > 1] if not selected: return base states, transitions, start, end = joint_constraint_tables() size = len(states) title = torch.tensor([a in (title_begin, title_inside) for a, _, _ in states]) augmented = torch.full((2 * size, 2 * size), -torch.inf) for seen in (0, 1): for before in range(size): for after in range(size): if title[after] and (seen or (states[after][0] == title_begin and title[before])): continue closed = seen or (bool(title[before]) and not bool(title[after])) augmented[seen * size + before, int(closed) * size + after] = transitions[before, after] starts = torch.cat((start, torch.full_like(start, -torch.inf))) ends = end.repeat(2) index = torch.tensor(selected, device=logits[0].device) outer_ids = torch.tensor([a for a, _, _ in states], device=logits[0].device) name_ids = torch.tensor([n for _, n, _ in states], device=logits[0].device) emissions = logits[0][index][..., outer_ids].float() + name_weight * logits[1][index][..., name_ids].float() lengths = [len(rows[i].text) for i in selected] paths = viterbi_paths(emissions.repeat(1, 1, 2), lengths, augmented, starts, ends) result = deepcopy(base) for i, path in zip(selected, paths, strict=True): outer = [states[s % size][0] for s in path] names = [states[s % size][1] for s in path] result[i] = prediction_from_labels(rows[i].identifier, rows[i].text, outer, names) return result
def predict_from_outputs(outputs: list[list[Tensor]], weights: Tensor, rows: list, calibrator: object | None, settings: dict, name_weight: float = 1.) -> list[dict]: from shared.span_tagger import preserve_baseline_structure if settings.get('consensus'): return consensus_predictions(outputs, weights, rows, calibrator, settings, name_weight) own_name_weight = float(settings.get('name_weight', name_weight)) logits = combine_scores(outputs, weights, settings) decoded = structural_predictions(logits, rows, own_name_weight, settings) if settings.get('lock_name_structure'): return fixed_mention_names(outputs, logits, decoded, rows, calibrator, settings, own_name_weight) if calibrator is not None and settings.get('name_cnn', True): correction = calibrator.correct(outputs, [row.text for row in rows]) scale = float(settings.get('name_cnn_scale', 1.)) corrected = [value + scale * delta for value, delta in zip(logits, correction, strict=True)] if settings.get('lock_cnn_outer_scores'): corrected[0] = logits[0] changed = structural_predictions(corrected, rows, own_name_weight, settings) decoded = [preserve_baseline_structure(before, after) for before, after in zip(decoded, changed, strict=True)] if settings.get('merge_title_fragments'): from shared.field_fragments import merge_field_fragments rules = [{'label': 'TITLE', 'gap_pattern': r'[\s.::;;\-–—]*'}] decoded = [merge_field_fragments(row.text, pred, rules) for row, pred in zip(rows, decoded, strict=True)] return decoded
def fixed_mention_names(outputs: list[list[Tensor]], logits: list[Tensor], baseline: list[dict], rows: list, calibrator: object | None, settings: dict, name_weight: float) -> list[dict]: from shared.dataset_schema import bio_labels from shared.span_tagger import OUTER_NAMES, citation_script_group, decode_predictions, preserve_baseline_structure names = logits[1].clone() if settings.get('name_routing') == 'mention': profiles = settings['name_profiles'] if len(outputs) != 4 or len(profiles) != 2 or any(len(p) != 4 or sum(p) <= 0 for p in profiles): raise ValueError('mention_routing_requires_two_valid_four_member_profiles') for i, (row, prediction) in enumerate(zip(rows, baseline, strict=True)): for person in prediction['contributors']: if person['kind'] != 'person': continue start, end = person['start'], person['end'] profile = profiles[citation_script_group(row.text[start:end])] total = sum(profile) names[i, start:end] = sum(outputs[m][1][i, start:end].float() * (weight / total) for m, weight in enumerate(profile)) if calibrator is not None and settings.get('name_cnn', True): names = names + float(settings.get('name_cnn_scale', 1.)) * calibrator.correct(outputs, [r.text for r in rows])[1] forced = torch.full_like(logits[0], -torch.inf) for i, (row, prediction) in enumerate(zip(rows, baseline, strict=True)): spans = [(f['label'], f['start'], f['end']) for f in prediction['fields']] spans += [(p['kind'], p['start'], p['end']) for p in prediction['contributors']] labels = torch.tensor(bio_labels(len(row.text), spans, OUTER_NAMES), device=forced.device) forced[i, torch.arange(len(row.text), device=forced.device), labels] = 0. changed = decode_predictions([forced, names], rows, 'joint', name_weight) return [preserve_baseline_structure(before, after) for before, after in zip(baseline, changed, strict=True)]
def choose_consensus(candidates: list[dict], references: list[dict], weights: list[list[float]], mode: str) -> dict: """正解を参照せず、固定抽出器間での範囲の一致だけを使って候補を選ぶ。""" def entities(row: dict) -> tuple[set, set, set]: return ({(f['label'], f['start'], f['end']) for f in row['fields']}, {(p['kind'], p['start'], p['end']) for p in row['contributors']}, {(k, v['start'], v['end']) for p in row['contributors'] for k, v in p['name_parts'].items()})
def agreement(a: set, b: set) -> float: return 2 * len(a & b) / (len(a) + len(b)) if a or b else 1.
evidence = [entities(row) for row in references] own_weights = [[.25] * 4] * 2 if mode == 'uniform' else weights best, best_score = candidates[0], -1. for candidate in candidates: parts = entities(candidate) score = 0. for i, other in enumerate(evidence): score += own_weights[0][i] * (2 * agreement(parts[0], other[0]) + agreement(parts[1], other[1])) if mode == 'full': score += own_weights[1][i] * agreement(parts[2], other[2]) if score > best_score + 1e-10: best, best_score = candidate, score from shared.span_tagger import preserve_baseline_structure return deepcopy(best) if mode == 'full' else preserve_baseline_structure(best, candidates[0])
def consensus_predictions(outputs: list[list[Tensor]], weights: Tensor, rows: list, calibrator: object | None, settings: dict, name_weight: float) -> list[dict]: if len(outputs) != 4: raise ValueError('consensus_requires_four_fixed_extractors') base_settings = {k: v for k, v in settings.items() if k != 'consensus'} pools = [predict_from_outputs(outputs, weights, rows, calibrator, base_settings, name_weight)] singles = [] for i in range(4): own = predict_from_outputs([outputs[i]], torch.ones_like(weights[:, :1]), rows, None, {'name_cnn': False}, name_weight) singles.append(own) members = [j for j in range(4) if j != i] leave_out = predict_from_outputs([outputs[j] for j in members], weights[:, members], rows, None, {'name_cnn': False}, name_weight) pools.extend((own, leave_out)) normalized = (weights / weights.sum(1, keepdim=True)).float().cpu() result = [] for index in range(len(rows)): profile = normalized if normalized.ndim == 2 else normalized[:, :, index] result.append(choose_consensus([pool[index] for pool in pools], [single[index] for single in singles], profile.tolist(), settings['consensus'])) return result1234567891011121314151617181920212223242526272829303132333435363738"""Return the best distinct paths through a small first-order state lattice."""import torchfrom torch import Tensor
def kbest_viterbi(emissions: Tensor, lengths: list[int], transitions: Tensor, initial: Tensor, final: Tensor, k: int) -> list[list[list[int]]]: values = emissions.float().cpu() batch, steps, states = values.shape if k < 1 or len(lengths) != batch or not lengths or min(lengths) < 1 or max(lengths) > steps: raise ValueError('invalid_kbest_dimensions') transitions, initial, final = transitions.float().cpu(), initial.float().cpu(), final.float().cpu() scores = values.new_full((batch, states, k), -torch.inf) scores[:, :, 0] = values[:, 0] + initial lengths_cpu = torch.as_tensor(lengths) back_pointers = [] for position in range(1, max(lengths)): candidates = scores[..., None] + transitions[None, :, None, :] best, prior = candidates.reshape(batch, states*k, states).topk(k, dim=1) proposed = best.transpose(1,2) + values[:, position, :, None] scores = torch.where((lengths_cpu > position)[:, None, None], proposed, scores) back_pointers.append(prior.transpose(1,2).numpy()) scores, endpoints = (scores + final[None, :, None]).reshape(batch,-1).topk(k, dim=1) finite = torch.isfinite(scores).tolist() all_paths = [] for row, (length, ends) in enumerate(zip(lengths, endpoints.tolist(), strict=True)): own = [] for rank, index in enumerate(ends): if not finite[row][rank]: continue state, lane = divmod(index,k) path = [state] for position in range(length-2,-1,-1): state, lane = divmod(int(back_pointers[position][row,state,lane]),k) path.append(state) own.append(list(reversed(path))) all_paths.append(own) return all_paths123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""訓練資料の姓・名の頻度と文字連鎖から、既存の人物範囲内の区切りを補助する。"""
from collections import Counterfrom copy import deepcopyfrom functools import lru_cacheimport hashlibimport mathimport reimport unicodedata
import numpy as np
from shared.dataset_schema import visible_valuefrom shared.training_lexicon import normalize_with_offsets
PARTS = ('family', 'given')JAPANESE = re.compile(r'[\u3040-\u30ff\u3400-\u9fff]')SEPARATORS = ' ,,、・·\t\n\r'
def normalize_part(value: str) -> str: return re.sub(r'\s+', '', unicodedata.normalize('NFKC', value).casefold())
def person_fold(family: str, given: str) -> int: key = normalize_part(family) + '\0' + normalize_part(given) return int(hashlib.sha256(key.encode()).hexdigest()[:16], 16) % 5
def character_pairs(value: str) -> list[str]: value = '^' + normalize_part(value) + '$' return [value[i:i + 2] for i in range(len(value) - 1)]
def build_prior(people: set[tuple[str, str]]) -> dict: """人物単位の固定fold=0を集計から除き、同一人物の重複を数えない。""" selected = {(normalize_part(f), normalize_part(g)) for f, g in people if f and g and person_fold(f, g) != 0} tables = {} for index, part in enumerate(PARTS): counts = Counter(pair[index] for pair in selected) grams = Counter(gram for pair in selected for gram in character_pairs(pair[index])) prefix = Counter() for gram, count in grams.items(): prefix[gram[0]] += count tables[part] = {'counts': dict(sorted(counts.items())), 'bigrams': dict(sorted(grams.items())), 'prefix': dict(sorted(prefix.items())), 'vocabulary': len({v[-1] for v in grams}) + 1} return {'schema': 'bibliography-name-boundary-prior/1', 'people': len(selected), 'excluded_person_fold': 0, 'tables': tables}
def prior_value(text: str, signature: tuple[int, int, int, int], prior: dict, character_weight: float) -> float: score = 0. for index, part in enumerate(PARTS): a, b = signature[index * 2:index * 2 + 2] value = normalize_part(text[a:b]) table = prior['tables'][part] score += math.log1p(table['counts'].get(value, 0)) if character_weight: grams = character_pairs(value) logp = sum(math.log((table['bigrams'].get(gram, 0) + .1) / (table['prefix'].get(gram[0], 0) + .1 * table['vocabulary'])) for gram in grams) score += character_weight * logp / len(grams) return score
def relative_signature(person: dict) -> tuple[int, int, int, int] | None: parts = person['name_parts'] if person['kind'] != 'person' or set(parts) != set(PARTS): return None return tuple(parts[part][edge] - person['start'] for part in PARTS for edge in ('start', 'end'))
@lru_cache(maxsize=100000)def partitions(text: str) -> tuple[tuple[int, int, int, int], ...]: """空白のない和文も分割するが、連続したラテン文字の途中では切らない。""" found = set() if not 2 <= len(text) <= 96: return () for cut in range(1, len(text)): if all((char.isalpha() or char in "'’") and not JAPANESE.search(char) for char in text[cut - 1:cut + 1]): continue left_a, left_b, right_a, right_b = 0, cut, cut, len(text) while left_a < left_b and text[left_a] in SEPARATORS: left_a += 1 while left_b > left_a and text[left_b - 1] in SEPARATORS: left_b -= 1 while right_a < right_b and text[right_a] in SEPARATORS: right_a += 1 while right_b > right_a and text[right_b - 1] in SEPARATORS: right_b -= 1 if left_a == left_b or right_a == right_b: continue found.add((left_a, left_b, right_a, right_b)) found.add((right_a, right_b, left_a, left_b)) return tuple(sorted(found))
def emission_value(scores: np.ndarray, signature: tuple[int, int, int, int]) -> float: tags = np.zeros(len(scores), dtype=np.int64) for index in (0, 1): a, b = signature[index * 2:index * 2 + 2] tags[a] = index * 2 + 1 tags[a + 1:b] = index * 2 + 2 return float(scores[np.arange(len(scores)), tags].sum(dtype=np.float64))
def alternatives(text: str, person: dict, scores: np.ndarray, prior: dict, character_weight: float, protected: set[str]) -> list[tuple[tuple[int, int, int, int], float, float]]: original = relative_signature(person) if original is None: return [] value = text[person['start']:person['end']] if normalize_with_offsets(value)[0] in protected: return [] candidates = partitions(value) if not candidates: return [] base = emission_value(scores, original) base_prior = prior_value(value, original, prior, character_weight) return [(signature, emission_value(scores, signature) - base, prior_value(value, signature, prior, character_weight) - base_prior) for signature in candidates if signature != original]
def apply_name_boundary_prior(text: str, prediction: dict, scores: np.ndarray, prior: dict, settings: dict, protected: set[str]) -> dict: result = deepcopy(prediction) if settings['strength'] == 0: return result for person in result['contributors']: start, end = person['start'], person['end'] choices = alternatives(text, person, scores[start:end], prior, settings['character_weight'], protected) if not choices: continue signature, emission, evidence = max(choices, key=lambda v: v[1] + settings['strength'] * v[2]) # 新しい分割を正当化する統計的根拠がある場合に限り変更する。 if evidence <= 0 or emission + settings['strength'] * evidence <= settings['margin']: continue person['name_parts'] = {part: {'start': start + signature[i * 2], 'end': start + signature[i * 2 + 1], 'value': visible_value(text[start + signature[i * 2]:start + signature[i * 2 + 1]], part)} for i, part in enumerate(PARTS)} return result
def merge_name_corrections(baseline: dict, first: dict, second: dict) -> dict: """独立した姓名補正を合わせ、二つの補正が食い違う人物は元の区切りを保つ。""" result = deepcopy(baseline) proposals = [{(p['kind'], p['start'], p['end']): p['name_parts'] for p in row['contributors']} for row in (first, second)] for person in result['contributors']: if person['kind'] != 'person': continue key = person['kind'], person['start'], person['end'] original = person['name_parts'] a, b = [values.get(key, original) for values in proposals] if a == b or b == original: person['name_parts'] = deepcopy(a) elif a == original: person['name_parts'] = deepcopy(b) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""原文の文字と文脈表現から、人物内の姓名ラベルを補正する小さなCNN。"""import numpy as npimport torchfrom torch import nnfrom copy import deepcopy
from shared.dataset_schema import visible_valuefrom shared.span_tagger import NAME_NAMES,OUTER_NAMES,bio_spans,joint_constraint_tables
def name_context_features(text:str,hidden:np.ndarray,logits:np.ndarray,start:int,end:int, context:int=4) -> tuple[np.ndarray,np.ndarray,int,int]: assert 0<=start<end<=len(text) and hidden.shape==(len(text),192) and logits.shape==(len(text),5) left=max(0,start-context);right=min(len(text),end+context) positions=np.arange(left,right) geometry=np.stack([(positions-start)/max(1,end-start),(positions>=start)&(positions<end)],-1).astype(np.float32) values=np.concatenate([hidden[left:right],logits[left:right],geometry],-1).astype(np.float16) encoded=np.zeros((right-left,4),dtype=np.int64) for i,char in enumerate(text[left:right]): raw=char.encode('utf-8');encoded[i,:len(raw)]=np.frombuffer(raw,dtype=np.uint8).astype(np.int64)+1 return values,encoded,start-left,end-left
class NameContextCNN(nn.Module): def __init__(self,width:int=32): super().__init__();self.width=width self.bytes=nn.Embedding(257,4,padding_idx=0) self.norm=nn.LayerNorm(199) self.conv1=nn.Conv1d(215,width,3,padding=1) self.conv2=nn.Conv1d(width,width,3,padding=1) self.output=nn.Conv1d(width,5,1) self.dropout=nn.Dropout(.1) nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
def forward(self,features:torch.Tensor,raw_bytes:torch.Tensor,lengths:torch.Tensor) -> torch.Tensor: valid=torch.arange(features.shape[1],device=features.device)[None,:]<lengths[:,None] mask=valid[:,None,:] embedded=self.bytes(raw_bytes).flatten(-2) values=torch.cat([self.norm(features),embedded],-1).transpose(1,2)*mask values=self.dropout(torch.nn.functional.gelu(self.conv1(values)))*mask values=self.dropout(torch.nn.functional.gelu(self.conv2(values)))*mask return features[...,192:197]+self.output(values).transpose(1,2)
def person_name_labels(person:dict) -> np.ndarray: labels=np.zeros(person['end']-person['start'],dtype=np.int64) for name,part in person['name_parts'].items(): start,end=part['start']-person['start'],part['end']-person['start'] label=1+2*NAME_NAMES.index(name);labels[start:end]=label+1;labels[start]=label return labels
def parts_from_name_labels(text:str,person:dict,labels:np.ndarray) -> dict: parts={} for name,start,end in bio_spans(labels.tolist(),NAME_NAMES): a,b=start+person['start'],end+person['start'] parts[name]={'start':a,'end':b,'value':visible_value(text[a:b],name)} assert parts and len(parts)<=2 return parts
class NamePathDecoder: def __init__(self,transitions:torch.Tensor,start:torch.Tensor,end:torch.Tensor,scale:float): states,legal,initial,final=joint_constraint_tables() begin=1+2*OUTER_NAMES.index('person') selected=[i for i,state in enumerate(states) if state[0] in (begin,begin+1)] own=[states[i] for i in selected] self.names=np.array([state[1] for state in own]) self.begin=np.array([state[0]==begin for state in own]) self.learned=transitions.detach().float().cpu().numpy()*scale self.start=start.detach().float().cpu().numpy()*scale self.end=end.detach().float().cpu().numpy()*scale self.transitions=legal[selected][:,selected].numpy()+self.learned[self.names[:,None],self.names[None,:]] self.final=final[selected].numpy()
def decode(self,logits:np.ndarray,at_start:bool=False,at_end:bool=False) -> np.ndarray: assert logits.ndim==2 and logits.shape[1]==5 and len(logits)>0 initial=self.start if at_start else self.learned[0] final=self.end if at_end else self.learned[:,0] scores=logits[0,self.names]+initial[self.names]+np.where(self.begin,0.,-10000.) history=[] for values in logits[1:]: candidates=scores[:,None]+self.transitions previous=candidates.argmax(0);history.append(previous) scores=candidates[previous,np.arange(len(previous))]+values[self.names]+np.where(self.begin,-10000.,0.) current=int(np.argmax(scores+self.final+final[self.names]));path=[current] for previous in reversed(history):current=int(previous[current]);path.append(current) return self.names[np.array(list(reversed(path)))]
def score(self,logits:np.ndarray,path:np.ndarray,at_start:bool=False,at_end:bool=False) -> float: initial=self.start if at_start else self.learned[0] final=self.end if at_end else self.learned[:,0] return float(logits[np.arange(len(path)),path].sum()+initial[path[0]]+final[path[-1]]+ self.learned[path[:-1],path[1:]].sum())
class NameContextRefiner: def __init__(self,model:NameContextCNN,head:nn.Module,residual_scale:float,minimum_gain:float): assert residual_scale>0 and minimum_gain>=0 self.model=model.cpu().eval();self.scale=residual_scale;self.minimum_gain=minimum_gain self.decoder=NamePathDecoder(head.names_transitions,head.names_start,head.names_end,head.transition_scale)
@torch.inference_mode() def predict(self,hidden:torch.Tensor,head:nn.Module,inputs:list[dict],predictions:list[dict]) -> list[dict]: characters=hidden.detach().float().cpu().numpy() name_logits=head.names(hidden).float().cpu().numpy() persons=[] for row_number,(inp,predicted) in enumerate(zip(inputs,predictions,strict=True)): assert inp['id']==predicted['id'] for person_number,person in enumerate(predicted['contributors']): if person['kind']!='person':continue features,raw_bytes,start,end=name_context_features(inp['text'],characters[row_number,:len(inp['text'])], name_logits[row_number,:len(inp['text'])],person['start'],person['end']) persons.append((row_number,person_number,features,raw_bytes,start,end)) result=list(predictions);changed=set() for begin in range(0,len(persons),256): rows=persons[begin:begin+256];longest=max(len(row[2]) for row in rows) features=np.zeros((len(rows),longest,199),np.float32);raw=np.zeros((len(rows),longest,4),np.int64);lengths=[] for i,row in enumerate(rows): length=len(row[2]);lengths.append(length);features[i,:length]=row[2];raw[i,:length]=row[3] values=torch.from_numpy(features) residuals=(self.model(values,torch.from_numpy(raw),torch.tensor(lengths))-values[...,192:197]).numpy() for i,(row_number,person_number,_,_,start,end) in enumerate(rows): inp=inputs[row_number];person=predictions[row_number]['contributors'][person_number] residual=residuals[i,start:end];base=name_logits[row_number,person['start']:person['end']] old=person_name_labels(person);mixed=base+self.scale*residual at_start=person['start']==0;at_end=person['end']==len(inp['text']) path=self.decoder.decode(mixed,at_start,at_end) if np.array_equal(old,path):continue positions=np.arange(len(old)) if float((residual[positions,path]-residual[positions,old]).sum())<=0:continue gain=self.decoder.score(mixed,path,at_start,at_end)-self.decoder.score(mixed,old,at_start,at_end) if gain<=self.minimum_gain:continue if row_number not in changed:result[row_number]=deepcopy(predictions[row_number]);changed.add(row_number) result[row_number]['contributors'][person_number]['name_parts']=parts_from_name_labels(inp['text'],person,path) return resultLICENSEAdded+202
NOTICE.mdAdded+9
README.mdAdded+60
bibform-lite-web.zipAdded+3
evaluation.jsonAdded+40
examples/input.jsonlAdded+2
licenses/ONNX-Runtime-MIT.txtAdded+21
licenses/ONNX-Runtime-ThirdPartyNotices.txtAdded
onnx/byte-network.onnxAdded+3
onnx/model.jsonAdded+2425
onnx/role-network.onnxAdded+3
pytorch/byte_architecture.jsonAdded+6
pytorch/byte_extractor.safetensorsAdded+3
pytorch/predict.pyAdded+89
pytorch/requirements.txtAdded+5
pytorch/resource_type.jsonAdded+38
pytorch/resource_type.safetensorsAdded+3
pytorch/resource_type_model.pyAdded+166
pytorch/resource_type_raw.jsonAdded+27
pytorch/resource_type_raw.safetensorsAdded+3
pytorch/shared/__init__.pyAdded+1
pytorch/shared/bibform_trial.pyAdded+225
pytorch/shared/bibform_trial_adapters.pyAdded+85
pytorch/shared/bibform_trial_model.pyAdded+750
pytorch/shared/compact_byte_extractor.pyAdded+62
pytorch/shared/compact_character_proxy.pyAdded+40
pytorch/shared/compact_edition_endpoint.pyAdded+77
pytorch/shared/compact_model_selector.pyAdded+105
pytorch/shared/compact_path_ranker.pyAdded+139
pytorch/shared/compact_score_blend.pyAdded+52
pytorch/shared/compact_title_acceptance.pyAdded+41
pytorch/shared/compact_title_pointer.pyAdded+112
pytorch/shared/compact_trial_head_storage.pyAdded+17
pytorch/shared/compact_version_spans.pyAdded+38
pytorch/shared/compact_weight_deltas.pyAdded+103
pytorch/shared/count_guided_candidates.pyAdded+49
pytorch/shared/count_guided_predictor.pyAdded+81
pytorch/shared/csl_spans.pyAdded+116
pytorch/shared/dataset_revision.pyAdded+79
pytorch/shared/dataset_schema.pyAdded+128
pytorch/shared/date_qualifier.pyAdded+37
pytorch/shared/doi_volume_prior.pyAdded+44
pytorch/shared/field_fragments.pyAdded+21
pytorch/shared/field_span_classifier.pyAdded+132
pytorch/shared/frozen_character_features.pyAdded+40
pytorch/shared/global_field_counts.pyAdded+51
pytorch/shared/inference_strategies.pyAdded+189
pytorch/shared/kbest_viterbi.pyAdded+38
pytorch/shared/name_boundary_prior.pyAdded+161
pytorch/shared/name_context_cnn.pyAdded+136