diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000000000000000000000000000000000000..6f652ff021ca091a231dfc414c228b06219107b6 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,9 @@ +# 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) diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c4be1d42e9b534b6b6fc7710af8dde8451edaf66 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +--- +license: apache-2.0 +language: + - ja + - en +tags: + - 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/` を開きます。静的ホストでも同じファイルを使えます。 + +```bash +python -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の環境で、取得したリポジトリのルートから実行します。 + +```bash +python -m pip install -r pytorch/requirements.txt +python 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) を参照してください。 diff --git a/bibform-lite-web.zip b/bibform-lite-web.zip new file mode 100644 index 0000000000000000000000000000000000000000..fa4f9bf4a4c7459240535a6104466ec2542c6ec5 --- /dev/null +++ b/bibform-lite-web.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c79d7e1aeb4b7baf3922d32bbfde336f009cb0260defbcd48f260e09134b7b1 +size 9255241 diff --git a/evaluation.json b/evaluation.json new file mode 100644 index 0000000000000000000000000000000000000000..9983d9a96705b85c55ee04ca5048cfd85c2ebbba --- /dev/null +++ b/evaluation.json @@ -0,0 +1,40 @@ +{ + "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 + } +} diff --git a/examples/input.jsonl b/examples/input.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d8f53adcca3cb534b5d2f7f38564197729e00e4d --- /dev/null +++ b/examples/input.jsonl @@ -0,0 +1,2 @@ +{"id":"example-en","text":"Taylor, J. (2023). Urban rainfall. Example Journal, 4(2), 11–24."} +{"id":"example-ja","text":"山田太郎(2024)「海辺の植物」架空研究誌、4巻2号、11–24頁。"} diff --git a/licenses/ONNX-Runtime-MIT.txt b/licenses/ONNX-Runtime-MIT.txt new file mode 100644 index 0000000000000000000000000000000000000000..48bc6bb4996ac924359e8e28b9ae88970e5ed3fc --- /dev/null +++ b/licenses/ONNX-Runtime-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/licenses/ONNX-Runtime-ThirdPartyNotices.txt b/licenses/ONNX-Runtime-ThirdPartyNotices.txt new file mode 100644 index 0000000000000000000000000000000000000000..75af6ad7e3db5c34e9ff923734ea49056c578d5f --- /dev/null +++ b/licenses/ONNX-Runtime-ThirdPartyNotices.txt @@ -0,0 +1,6369 @@ +THIRD PARTY SOFTWARE NOTICES AND INFORMATION + +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at http://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. + +_____ + +Intel Math Kernel Library (Intel MKL) + +Intel Simplified Software License (Version April 2018) + +Copyright (c) 2018 Intel Corporation. + +Use and Redistribution. You may use and redistribute the software (the “Software”), without modification, +provided the following conditions are met: + +* Redistributions must reproduce the above copyright notice and the following terms of use in the Software +and in the documentation and/or other materials provided with the distribution. + +* Neither the name of Intel nor the names of its suppliers may be used to endorse or promote products +derived from this Software without specific prior written permission. + +* No reverse engineering, decompilation, or disassembly of this Software is permitted. + +Limited patent license. Intel grants you a world-wide, royalty-free, non-exclusive license under patents it now +or hereafter owns or controls to make, have made, use, import, offer to sell and sell (“Utilize”) this Software, +but solely to the extent that any such patent is necessary to Utilize the Software alone. The patent license +shall not apply to any combinations which include this software. No hardware per se is licensed hereunder. + +Third party and other Intel programs. “Third Party Programs” are the files listed in the “third-party-programs.txt” +text file that is included with the Software and may include Intel programs under separate license terms. +Third Party Programs, even if included with the distribution of the Materials, are governed by +separate license terms and those license terms solely govern your use of those programs. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. THIS SOFTWARE IS +NOT INTENDED FOR USE IN SYSTEMS OR APPLICATIONS WHERE FAILURE OF THE SOFTWARE +MAY CAUSE PERSONAL INJURY OR DEATH AND YOU AGREE THAT YOU ARE FULLY RESPONSIBLE FOR ANY +CLAIMS, COSTS, DAMAGES, EXPENSES, AND ATTORNEYS’ FEES ARISING OUT OF ANY SUCH USE, +EVEN IF ANY CLAIM ALLEGES THAT INTEL WAS NEGLIGENT REGARDING THE DESIGN OR MANUFACTURE OF +THE MATERIALS. + +LIMITATION OF LIABILITY. IN NO EVENT WILL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. YOU AGREE TO INDEMNIFY AND HOLD INTEL HARMLESS AGAINST ANY CLAIMS +AND EXPENSES RESULTING FROM YOUR USE OR UNAUTHORIZED USE OF THE SOFTWARE. + +No support. Intel may make changes to the Software, at any time without notice, and is not obligated to +support, update or provide training for the Software. + +Termination. Intel may terminate your right to use the Software in the event of your breach of this Agreement +and you fail to cure the breach within a reasonable period of time. + +Feedback. Should you provide Intel with comments, modifications, corrections, enhancements or other input +(“Feedback”) related to the Software Intel will be free to use, disclose, reproduce, license or otherwise +distribute or exploit the Feedback in its sole discretion without any obligations or restrictions of any kind, +including without limitation, intellectual property rights or licensing obligations. + +Compliance with laws. You agree to comply with all relevant laws and regulations governing your use, +transfer, import or export (or prohibition thereof) of the Software. + +Governing law. All disputes will be governed by the laws of the United States of America and the State of +Delaware without reference to conflict of law principles and subject to the exclusive jurisdiction of the state or +federal courts sitting in the State of Delaware, and each party agrees that it submits to the personal +jurisdiction and venue of those courts and waives any objections. The United Nations Convention on +Contracts for the International Sale of Goods (1980) is specifically excluded and will not apply to the +Software. + +*Other names and brands may be claimed as the property of others. + +_____ + +protocolbuffers/protobuf + +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + +_____ + +madler/zlib + +The deflate format used by zlib was defined by Phil Katz. The deflate and +zlib specifications were written by L. Peter Deutsch. Thanks to all the +people who reported problems and suggested various improvements in zlib; they +are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +_____ + +pybind/pybind11 + +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. + +_____ + +onnx +Open Neural Network Exchange + +Copyright (c) Facebook, Inc. and Microsoft Corporation. All rights reserved. + + 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. + +_____ + +Eigen + +MPL v2.0 +Mozilla Public License Version 2.0 + + +================================== + +1. Definitions + +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions + +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities + +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination + +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + +_____ + +intel/dnnl + +Copyright 2016-2018 Intel Corporation + +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. + +sub-components: + +xbyak + +Copyright (c) 2007 MITSUNARI Shigeo. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +Neither the name of the copyright owner nor the names of its contributors may +be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Microsoft GSL + +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 +THE SOFTWARE. + +_____ + +Tensorflow + +Copyright 2018 The TensorFlow Authors. All rights reserved. + +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 2017, The TensorFlow Authors. + + 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. + +_____ + +Microsoft Cognitive Toolkit (CNTK) + +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +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 THE SOFTWARE. + +_____ + +NumPy License + +Copyright (c) 2005, NumPy Developers + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Pytorch / Caffe2 + +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +_____ + +Caffe + +COPYRIGHT + +All contributions by the University of California: +Copyright (c) 2014-2017 The Regents of the University of California (Regents) +All rights reserved. + +All other contributions: +Copyright (c) 2014-2017, the respective contributors +All rights reserved. + +Caffe uses a shared copyright model: each contributor holds copyright over +their contributions to Caffe. The project versioning records all such +contribution and copyright details. If a contributor wants to further mark +their specific copyright on a particular contribution, they should indicate +their copyright solely in the commit message of the change when it is +committed. + +LICENSE + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +CONTRIBUTION AGREEMENT + +By contributing to the BVLC/caffe repository through pull-request, comment, +or otherwise, the contributor releases their content to the +license and copyright terms herein. + +_____ + +The LLVM Compiler Infrastructure + +============================================================================== +LLVM Release License +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 WITH THE +SOFTWARE. + +============================================================================== +Copyrights and Licenses for Third Party Software Distributed with LLVM: +============================================================================== +The LLVM software contains code written by third parties. Such software will +have its own individual LICENSE.TXT file in the directory in which it appears. +This file will describe the copyrights, license, and restrictions which apply +to that code. + +The disclaimer of warranty in the University of Illinois Open Source License +applies to all code in the LLVM Distribution, and nothing in any of the +other licenses gives permission to use the names of the LLVM Team or the +University of Illinois to endorse or promote products derived from this +Software. + +The following pieces of software have additional or alternate copyrights, +licenses, and/or restrictions: + +Program Directory +------- --------- +Google Test llvm/utils/unittest/googletest +OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex} +pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT} +ARM contributions llvm/lib/Target/ARM/LICENSE.TXT +md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h + +_____ + +google/benchmark + + + 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. + +CONTRIBUTORS + +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. +# +# Names should be added to this file as: +# Name +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Billy Robert O'Neal III +Chris Kennelly +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dominic Hamon +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +John Millikin +Jussi Knuuttila +Kai Wolf +Kishan Kumar +Kaito Udagawa +Lei Xu +Matt Clarkson +Maxim Vafin +Nick Hutchinson +Oleksandr Sochka +Pascal Leroy +Paul Redmond +Pierre Phaneuf +Radoslav Yovchev +Raul Marin +Ray Glover +Robert Guo +Roman Lebedev +Shuo Chen +Tobias Ulvgård +Tom Madams +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +AUTHORS + +# This is the official list of benchmark authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. +# +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Carto +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dirac Research +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Google Inc. +International Business Machines Corporation +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +Jussi Knuuttila +Kaito Udagawa +Kishan Kumar +Lei Xu +Matt Clarkson +Maxim Vafin +MongoDB Inc. +Nick Hutchinson +Oleksandr Sochka +Paul Redmond +Radoslav Yovchev +Roman Lebedev +Shuo Chen +Steinar H. Gunderson +Stripe, Inc. +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +_____ + +HalideIR + +Copyright (c) 2016 HalideIR contributors +Copyright (c) 2012-2014 MIT CSAIL, Google Inc., and other contributors +HalideIR is derived from the Halide project. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE. + +_____ + +Distributed Machine Learning Common Codebase + +Copyright (c) 2015 by Contributors + +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. + +_____ + +DLPack: Open In Memory Tensor Structure + + 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 2017 by Contributors + + 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. + +_____ + +HowardHinnant/date + +The source code in this project is released using the MIT License. There is no +global license for the project because each file is licensed individually with +different author names and/or dates. + +If you contribute to this project, please add your name to the license of each +file you modify. If you have already contributed to this project and forgot to +add your name to the license, please feel free to submit a new P/R to add your +name to the license in each file you modified. + +For convenience, here is a copy of the MIT license found in each file except +without author names or dates: + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ + +FreeBSD: getopt.c file + +Copyright (c) 1987, 1993, 1994 +The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the University nor the names of its contributors +may be used to endorse or promote products derived from this software +without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +_____ + + +google/googletest + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +G3log : Asynchronous logger with Dynamic Sinks + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, 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 THE SOFTWARE. + +For more information, please refer to +_____ + +Scikit-learn + +Copyright (c) 2007–2018 The scikit-learn developers. +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + c. Neither the name of the Scikit-learn Developers nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +_____ + +google/re2 + +Copyright (c) 2009 The RE2 Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +onnx/onnx-tensorrt + +MIT License + +Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +Copyright (c) 2018 Open Neural Network Exchange + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ +nvidia/cutlass + +Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ +Boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +_____ + +JDAI-CV/DNNLibrary + + 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 [2019] [JD.com Inc. JD AI] + + 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. + + +_____ + +google/flatbuffers + + + 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 2014 Google Inc. + + 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. + + +_____ + +google/glog + +Copyright (c) 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +A function gettimeofday in utilities.cc is based on + +http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd + +The license of this code is: + +Copyright (c) 2003-2008, Jouni Malinen and contributors +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name(s) of the above-listed copyright holder(s) nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +abseil-cpp +https://github.com/abseil/abseil-cpp + + Apache License + Version 2.0, January 2004 + https://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 + + https://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. + + +_____ + +microsoft/wil + +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE + +_____ + +nlohmann/json + +MIT License + +Copyright (c) 2013-2019 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ + +dcleblanc/SafeInt + +MIT License + +Copyright (c) 2018 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ +Open MPI + +3-Clause BSD License + +Most files in this release are marked with the copyrights of the +organizations who have edited them. The copyrights below are in no +particular order and generally reflect members of the Open MPI core +team who have contributed code to this release. The copyrights for +code used under license from other parties are included in the +corresponding files. + +Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana + University Research and Technology + Corporation. All rights reserved. +Copyright (c) 2004-2017 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. +Copyright (c) 2004-2010 High Performance Computing Center Stuttgart, + University of Stuttgart. All rights reserved. +Copyright (c) 2004-2008 The Regents of the University of California. + All rights reserved. +Copyright (c) 2006-2017 Los Alamos National Security, LLC. All rights + reserved. +Copyright (c) 2006-2017 Cisco Systems, Inc. All rights reserved. +Copyright (c) 2006-2010 Voltaire, Inc. All rights reserved. +Copyright (c) 2006-2017 Sandia National Laboratories. All rights reserved. +Copyright (c) 2006-2010 Sun Microsystems, Inc. All rights reserved. + Use is subject to license terms. +Copyright (c) 2006-2017 The University of Houston. All rights reserved. +Copyright (c) 2006-2009 Myricom, Inc. All rights reserved. +Copyright (c) 2007-2017 UT-Battelle, LLC. All rights reserved. +Copyright (c) 2007-2017 IBM Corporation. All rights reserved. +Copyright (c) 1998-2005 Forschungszentrum Juelich, Juelich Supercomputing + Centre, Federal Republic of Germany +Copyright (c) 2005-2008 ZIH, TU Dresden, Federal Republic of Germany +Copyright (c) 2007 Evergrid, Inc. All rights reserved. +Copyright (c) 2008 Chelsio, Inc. All rights reserved. +Copyright (c) 2008-2009 Institut National de Recherche en + Informatique. All rights reserved. +Copyright (c) 2007 Lawrence Livermore National Security, LLC. + All rights reserved. +Copyright (c) 2007-2017 Mellanox Technologies. All rights reserved. +Copyright (c) 2006-2010 QLogic Corporation. All rights reserved. +Copyright (c) 2008-2017 Oak Ridge National Labs. All rights reserved. +Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved. +Copyright (c) 2009-2015 Bull SAS. All rights reserved. +Copyright (c) 2010 ARM ltd. All rights reserved. +Copyright (c) 2016 ARM, Inc. All rights reserved. +Copyright (c) 2010-2011 Alex Brick . All rights reserved. +Copyright (c) 2012 The University of Wisconsin-La Crosse. All rights + reserved. +Copyright (c) 2013-2016 Intel, Inc. All rights reserved. +Copyright (c) 2011-2017 NVIDIA Corporation. All rights reserved. +Copyright (c) 2016 Broadcom Limited. All rights reserved. +Copyright (c) 2011-2017 Fujitsu Limited. All rights reserved. +Copyright (c) 2014-2015 Hewlett-Packard Development Company, LP. All + rights reserved. +Copyright (c) 2013-2017 Research Organization for Information Science (RIST). + All rights reserved. +Copyright (c) 2017-2018 Amazon.com, Inc. or its affiliates. All Rights + reserved. +Copyright (c) 2018 DataDirect Networks. All rights reserved. +Copyright (c) 2018-2019 Triad National Security, LLC. All rights reserved. + +$COPYRIGHT$ + +Additional copyrights may follow + +$HEADER$ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +The copyright holders provide no reassurances that the source code +provided does not infringe any patent, copyright, or any other +intellectual property rights of third parties. The copyright holders +disclaim any liability to any recipient for claims brought against +recipient by any third party for infringement of that parties +intellectual property rights. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +The Android Open Source Project + +Copyright (C) 2017 The Android Open Source Project +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. + +------ + +libprotobuf-mutator + + 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. + + ----- + + openucx/ucx + https://github.com/openucx/ucx + + Copyright (c) 2014-2015 UT-Battelle, LLC. All rights reserved. + Copyright (C) 2014-2020 Mellanox Technologies Ltd. All rights reserved. + Copyright (C) 2014-2015 The University of Houston System. All rights reserved. + Copyright (C) 2015 The University of Tennessee and The University + of Tennessee Research Foundation. All rights reserved. + Copyright (C) 2016-2020 ARM Ltd. All rights reserved. + Copyright (c) 2016 Los Alamos National Security, LLC. All rights reserved. + Copyright (C) 2016-2020 Advanced Micro Devices, Inc. All rights reserved. + Copyright (C) 2019 UChicago Argonne, LLC. All rights reserved. + Copyright (c) 2018-2020 NVIDIA CORPORATION. All rights reserved. + Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + Copyright (C) 2016-2020 Stony Brook University. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ----- + + From PyTorch: + + Copyright (c) 2016- Facebook, Inc (Adam Paszke) + Copyright (c) 2014- Facebook, Inc (Soumith Chintala) + Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) + Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) + Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) + Copyright (c) 2011-2013 NYU (Clement Farabet) + Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) + Copyright (c) 2006 Idiap Research Institute (Samy Bengio) + Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + + From Caffe2: + + Copyright (c) 2016-present, Facebook Inc. All rights reserved. + + All contributions by Facebook: + Copyright (c) 2016 Facebook Inc. + + All contributions by Google: + Copyright (c) 2015 Google Inc. + All rights reserved. + + All contributions by Yangqing Jia: + Copyright (c) 2015 Yangqing Jia + All rights reserved. + + All contributions from Caffe: + Copyright(c) 2013, 2014, 2015, the respective contributors + All rights reserved. + + All other contributions: + Copyright(c) 2015, 2016 the respective contributors + All rights reserved. + + Caffe2 uses a copyright model similar to Caffe: each contributor holds + copyright over their contributions to Caffe2. The project versioning records + all such contribution and copyright details. If a contributor wants to further + mark their specific copyright on a particular contribution, they should + indicate their copyright solely in the commit message of the change when it is + committed. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +_____ + + mpi4py + https://github.com/mpi4py/mpi4py/ + + ======================= + LICENSE: MPI for Python + ======================= + + :Author: Lisandro Dalcin + :Contact: dalcinl@gmail.com + + + Copyright (c) 2019, Lisandro Dalcin. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +huggingface/transformers + + 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. +_____ +msgpack/msgpack-python + +Copyright (C) 2008-2011 INADA Naoki + + 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. +_____ +lanpa/tensorboardX + +MIT License + +Copyright (c) 2017 Tzu-Wei Huang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. +_____ +tensorflow/tensorboard + +Copyright 2017 The TensorFlow Authors. All rights reserved. + + 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 2017, The TensorFlow Authors. + + 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. + + +_____ + +cerberus + +Cerberus is a lightweight and extensible data validation library for Python. + +ISC License + +Copyright (c) 2012-2016 Nicola Iarocci. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +MurmurHash3 + +MIT license + +https://github.com/aappleby/smhasher + +SMHasher is a test suite designed to test the distribution, collision, and +performance properties of non-cryptographic hash functions. +This is the home for the MurmurHash family of hash functions along with the +SMHasher test suite used to verify them. +SMHasher is released under the MIT license. +All MurmurHash versions are public domain software, and the author disclaims all copyright to their code. + +_____ + +gtest-ios-framework + +https://github.com/mestevens/gtest-ios-framework + +Copyright (c) 2013 Matthew Stevens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE. + +_____ + +DLPack + +https://github.com/dmlc/dlpack + + 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 2017 by Contributors + + 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. + +_____ + +emsdk + +MIT/Expat license + +https://github.com/emscripten-core/emsdk + +Copyright (c) 2018 Emscripten authors (see AUTHORS in Emscripten) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +---------------------------------------------------------------------------- + +This is the MIT/Expat License. For more information see: + +1. http://www.opensource.org/licenses/mit-license.php + +2. http://en.wikipedia.org/wiki/MIT_License + +_____ + +coremltools + +BSD-3-Clause License + +https://github.com/apple/coremltools + +Copyright (c) 2020, Apple Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +© 2021 GitHub, Inc. + +_____ + +react-native + +MIT License + +https://github.com/facebook/react-native + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ + +pytorch/cpuinfo + +BSD 2-Clause "Simplified" License + +https://github.com/pytorch/cpuinfo + +Copyright (c) 2019 Google LLC +Copyright (c) 2017-2018 Facebook Inc. +Copyright (C) 2012-2017 Georgia Institute of Technology +Copyright (C) 2010-2012 Marat Dukhan + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +SQLite Is Public Domain + +All of the code and documentation in SQLite has been dedicated to the public +domain by the authors. All code authors, and representatives of the companies +they work for, have signed affidavits dedicating their contributions to the +public domain and originals of those signed affidavits are stored in a firesafe +at the main offices of Hwaci. Anyone is free to copy, modify, publish, use, +compile, sell, or distribute the original SQLite code, either in source code +form or as a compiled binary, for any purpose, commercial or non-commercial, +and by any means. + +The previous paragraph applies to the deliverable code and documentation in +SQLite - those parts of the SQLite library that you actually bundle and ship +with a larger application. Some scripts used as part of the build process (for +example the "configure" scripts generated by autoconf) might fall under other +open-source licenses. Nothing from these build scripts ever reaches the final +deliverable SQLite library, however, and so the licenses associated with those +scripts should not be a factor in assessing your rights to copy and use the +SQLite library. + +All of the deliverable code in SQLite has been written from scratch. No code +has been taken from other projects or from the open internet. Every line of +code can be traced back to its original author, and all of those authors have +public domain dedications on file. So the SQLite code base is clean and is +uncontaminated with licensed code from other projects. + +_____ + +google/XNNPACK + +BSD License + +For XNNPACK software + +Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +Copyright 2019 Google LLC + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +google/sentencepiece, https://github.com/google/sentencepiece +(included when statically linked with onnxruntime-extensions) + + 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. + +_____ + +dlfcn-win32/dlfcn-win32 is licensed under the MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 +THE SOFTWARE. + +_____ + +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh + +Pillow is the friendly PIL fork. It is + + Copyright © 2010-2023 by Alex Clark and contributors + +Like PIL, Pillow is licensed under the open source HPND License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +openssl/openssl, https://github.com/openssl/openssl + + Apache License + Version 2.0, January 2004 + https://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 + +_____ + +Tencent/rapidjson, https://github.com/Tencent/rapidjson + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Open Source Software Licensed Under the JSON License: +-------------------------------------------------------------------- + +json.org +Copyright (c) 2002 JSON.org +All Rights Reserved. + +JSON_checker +Copyright (c) 2002 JSON.org +All Rights Reserved. + + +Terms of the JSON License: +--------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE. + +_____ + +boostorg/boost, https://github.com/boostorg/boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +_____ + +libb64/libb64, https://github.com/libb64/libb64 + +Copyright-Only Dedication (based on United States law) or Public Domain Certification + +The person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below. + +A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain. + +Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. + +Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. + +_____ + +posix pthread library, https://sourceforge.net/projects/pthreads4w + + + 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. + +_____ + +Triton Inference Server & Client, https://github.com/triton-inference-server + +Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of NVIDIA CORPORATION nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +microsoft/mimalloc, https://github.com/microsoft/mimalloc + +MIT License + +Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. + +_____ + +TensorFlow.js + +https://github.com/tensorflow/tfjs + + + 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. + +—— + +curl/curl + +https://github.com/curl + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (C) Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + +_____ + +Mbed TLS + +https://github.com/Mbed-TLS/mbedtls + +Copyright The Mbed TLS Contributors + +Mbed TLS is available under the Apache License 2.0 OR the GNU General Public +License, version 2 or later. This distribution uses Mbed TLS under the Apache +License 2.0. The full Apache License 2.0 terms are reproduced above in this +file. + +_____ + +Intel neural-compressor + +https://github.com/intel/neural-compressor + + 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 + + ============================================================================ + + Copyright 2016-2019 Intel Corporation + Copyright 2018 YANDEX LLC + + 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. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. + +_____ + +FlashAttention, https://github.com/Dao-AILab/flash-attention + +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +neural-speed + +https://github.com/intel/neural-speed + + Apache License + 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 + + ============================================================================ + + Copyright 2016-2019 Intel Corporation + Copyright 2018 YANDEX LLC + + 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. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. + +_____ + +dawn + +https://dawn.googlesource.com/dawn + + BSD 3-Clause License + + Copyright 2017-2023 The Dawn & Tint Authors + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +KleidiAI + +https://gitlab.arm.com/kleidi/kleidiai + +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 + +Copyright 2024-2025 Arm Limited and/or its affiliates + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +microsoft/cpp_client_telemetry, https://github.com/microsoft/cpp_client_telemetry/ + +Apache License + +Copyright (c) Microsoft Corporation. All rights reserved. + + 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. +_____ +DeepSeek DeepGEMM (https://github.com/deepseek-ai/DeepGEMM) +Commit: 559d79fb6994a58b8a15b4b93bf13ccc16edf247 + +MIT License + +Copyright (c) 2025 DeepSeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/onnx/byte-network.onnx b/onnx/byte-network.onnx new file mode 100644 index 0000000000000000000000000000000000000000..f797383db1745bac08d9f3aa4aa9443e3ce7dbb8 --- /dev/null +++ b/onnx/byte-network.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a953c3ab5826334cb0b47c528291b888179d2666654d74775f7904a210aad03 +size 5831945 diff --git a/onnx/model.json b/onnx/model.json new file mode 100644 index 0000000000000000000000000000000000000000..a273ca141df1c4cf49f0b3666771d3839fadd76b --- /dev/null +++ b/onnx/model.json @@ -0,0 +1,2425 @@ +{ + "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 + } +} diff --git a/onnx/role-network.onnx b/onnx/role-network.onnx new file mode 100644 index 0000000000000000000000000000000000000000..c2443ba1f253ef9be2d103b19a745659a4cded4d --- /dev/null +++ b/onnx/role-network.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:029d9fde693486dd86c24f5031d2223e217e12e2c03a864a5db1f1440ff2fa97 +size 110656 diff --git a/pytorch/byte_architecture.json b/pytorch/byte_architecture.json new file mode 100644 index 0000000000000000000000000000000000000000..1a5f8f7e7a73114fc19f1c5c03d8c65c9c7f1735 --- /dev/null +++ b/pytorch/byte_architecture.json @@ -0,0 +1,6 @@ +{ + "width": 192, + "attention_layers": 14, + "parameters": 4656225, + "weights_format": "int8" +} diff --git a/pytorch/byte_extractor.safetensors b/pytorch/byte_extractor.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..f78ebdfe44eb0511aee9e5315f0f7912679856cf --- /dev/null +++ b/pytorch/byte_extractor.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eac58cb50520d169ca5f8349c9ed058b2b91ff8c35452ec0eae56c74b481e2c9 +size 4800240 diff --git a/pytorch/predict.py b/pytorch/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..bc02285d36bfbb885183086f7e5b4e1d6c51f175 --- /dev/null +++ b/pytorch/predict.py @@ -0,0 +1,89 @@ +"""Run the independent byte extractor in a standalone package.""" + +import argparse +import json +from pathlib import Path + +from safetensors.torch import load_file +import torch +from resource_type_model import ResourceTypeOutput, TypeFieldCountEvidence, pool_context + +from shared.compact_byte_extractor import CompactByteExtractor +from 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 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) diff --git a/pytorch/resource_type_raw.json b/pytorch/resource_type_raw.json new file mode 100644 index 0000000000000000000000000000000000000000..ad71bda5260e0754b268b99ead1c2dcb2f007613 --- /dev/null +++ b/pytorch/resource_type_raw.json @@ -0,0 +1,27 @@ +{ + "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 +} diff --git a/pytorch/resource_type_raw.safetensors b/pytorch/resource_type_raw.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..02b17a7938ebd44a677964b48631ad2b92c7b60a --- /dev/null +++ b/pytorch/resource_type_raw.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b49fd0accea70d1138473da425a326311d9cd9574fceb97da21df42f62f43e5 +size 786968 diff --git a/pytorch/shared/__init__.py b/pytorch/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26f5fc498a9c9942e4660430399089c3e73a5a1f --- /dev/null +++ b/pytorch/shared/__init__.py @@ -0,0 +1 @@ +"""分析スクリプトで共有するモジュール。""" diff --git a/pytorch/shared/bibform_trial.py b/pytorch/shared/bibform_trial.py new file mode 100644 index 0000000000000000000000000000000000000000..5b9f61735a0acc4a0a2e35cc93eca5f17c8229d8 --- /dev/null +++ b/pytorch/shared/bibform_trial.py @@ -0,0 +1,225 @@ +"""bibformDatasetTrialの役割付き文字範囲と、原文だけを使う評価契約。""" +from collections import Counter, defaultdict +from copy import deepcopy +import hashlib +import json +import re +import random + +from shared.csl_spans import canonical_annotations +from shared.dataset_schema import FIELD_MAP, visible_value +from 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())}} diff --git a/pytorch/shared/bibform_trial_adapters.py b/pytorch/shared/bibform_trial_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e0bdfd6a5ddc0a92ceec68396ab79f2b48892f --- /dev/null +++ b/pytorch/shared/bibform_trial_adapters.py @@ -0,0 +1,85 @@ +"""既存の重みを保存したまま、選んだ線形層へ小さな学習可能な差分を加える。""" +from pathlib import Path + +from safetensors.torch import load_file +import torch +from 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']) diff --git a/pytorch/shared/bibform_trial_model.py b/pytorch/shared/bibform_trial_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f7334ff1492c9a1e2d122d3672588a17c93c96 --- /dev/null +++ b/pytorch/shared/bibform_trial_model.py @@ -0,0 +1,750 @@ +"""原文の固定文字表現から、書誌範囲・姓名・人物ごとの複数役割を予測する。""" +from pathlib import Path +import json + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from safetensors.torch import load_file + +from shared.bibform_trial import FIELDS, ROLES, validate +from shared.dataset_schema import bio_labels +from shared.span_tagger import EncodedCitation, OUTER_NAMES, NAME_NAMES, load_package +from shared.inference_strategies import structural_predictions +from shared.range_extraction import RANGE_TYPES, prediction_from_ranges +from 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 row diff --git a/pytorch/shared/compact_byte_extractor.py b/pytorch/shared/compact_byte_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..913ec0d0adbd9ab84ab90297c93c97db9943aabb --- /dev/null +++ b/pytorch/shared/compact_byte_extractor.py @@ -0,0 +1,62 @@ +"""Extract citations from UTF-8 bytes aligned to the original character positions.""" + +import numpy as np +import torch +from torch import nn + +from shared.bibform_trial import trim_whitespace_boundaries +from shared.bibform_trial_model import TrialBIO,utf8_character_ids +from shared.range_extraction import position_features + + +WIDTH = 144 +DEPTH = 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)] diff --git a/pytorch/shared/compact_character_proxy.py b/pytorch/shared/compact_character_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..034ba38e336daa29b8d155e5ae8b6e9dc9d2be61 --- /dev/null +++ b/pytorch/shared/compact_character_proxy.py @@ -0,0 +1,40 @@ +"""A small character branch using the compact encoder's existing context.""" + +import torch +from torch import Tensor, nn +from 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 * mask diff --git a/pytorch/shared/compact_edition_endpoint.py b/pytorch/shared/compact_edition_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..8c651193775199a8cb5020c2aa508fb62ee35dd8 --- /dev/null +++ b/pytorch/shared/compact_edition_endpoint.py @@ -0,0 +1,77 @@ +"""Predict the end of a detected edition while keeping its original start.""" + +import numpy as np +import torch +from torch import nn + +from shared.bibform_trial_model import RawCharacterEncoder, utf8_character_ids +from 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 updated diff --git a/pytorch/shared/compact_model_selector.py b/pytorch/shared/compact_model_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..220229056b5eed14e3c7a10e5d98f09afa079b68 --- /dev/null +++ b/pytorch/shared/compact_model_selector.py @@ -0,0 +1,105 @@ +"""Choose between frozen extraction predictions using both models' character scores.""" + +import numpy as np +import torch + +from shared.bibform_trial import ROLES, signature +from 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 base diff --git a/pytorch/shared/compact_path_ranker.py b/pytorch/shared/compact_path_ranker.py new file mode 100644 index 0000000000000000000000000000000000000000..83324aac67af6d9099d21204ec87363f5ed6e787 --- /dev/null +++ b/pytorch/shared/compact_path_ranker.py @@ -0,0 +1,139 @@ +"""Score plausible alternative character paths using their model evidence.""" +from collections import Counter + +import numpy as np +import torch +from torch import nn + +from shared.bibform_trial import FIELDS, ROLES, signature +from shared.count_guided_candidates import count_vector +from shared.dataset_schema import bio_labels +from shared.kbest_viterbi import kbest_viterbi +from 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 selected diff --git a/pytorch/shared/compact_score_blend.py b/pytorch/shared/compact_score_blend.py new file mode 100644 index 0000000000000000000000000000000000000000..13161247c511bf6e01a02d7ff9421dc086ca3f17 --- /dev/null +++ b/pytorch/shared/compact_score_blend.py @@ -0,0 +1,52 @@ +"""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 predictions diff --git a/pytorch/shared/compact_title_acceptance.py b/pytorch/shared/compact_title_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..87a8bd647b9d4db431d196806bcaf40ac4ca3097 --- /dev/null +++ b/pytorch/shared/compact_title_acceptance.py @@ -0,0 +1,41 @@ +"""Compare support for an absorbed title span in both frozen extractors.""" + +import numpy as np +import 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_MARGINthreshold: + result[index] = proposal + return result diff --git a/pytorch/shared/compact_title_pointer.py b/pytorch/shared/compact_title_pointer.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e5570b1d14fb8c10c1b6b4cd7694af3c122593 --- /dev/null +++ b/pytorch/shared/compact_title_pointer.py @@ -0,0 +1,112 @@ +"""Score complete title spans from a frozen character representation.""" + +import numpy as np +import torch +from 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]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]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_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 adjusted diff --git a/pytorch/shared/compact_trial_head_storage.py b/pytorch/shared/compact_trial_head_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..781ea37f5daa0d24580b51fd5848dc77d68f3885 --- /dev/null +++ b/pytorch/shared/compact_trial_head_storage.py @@ -0,0 +1,17 @@ +"""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) diff --git a/pytorch/shared/compact_version_spans.py b/pytorch/shared/compact_version_spans.py new file mode 100644 index 0000000000000000000000000000000000000000..b26165d903d82037483c874d2899061e4142f641 --- /dev/null +++ b/pytorch/shared/compact_version_spans.py @@ -0,0 +1,38 @@ +"""Distinguish version values from volume values without changing span offsets.""" + +import numpy as np +import torch + +from shared.dataset_schema import visible_value +from 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 result diff --git a/pytorch/shared/compact_weight_deltas.py b/pytorch/shared/compact_weight_deltas.py new file mode 100644 index 0000000000000000000000000000000000000000..c77b3ac6469dff9b333c988ef7075dd65c9f9a8a --- /dev/null +++ b/pytorch/shared/compact_weight_deltas.py @@ -0,0 +1,103 @@ +"""Share identical resources and losslessly store differences between model packages.""" + +from compression import zstd +import hashlib +import json +from 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() diff --git a/pytorch/shared/count_guided_candidates.py b/pytorch/shared/count_guided_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..fed8ee6e5584721b504984c8c56fb9c1ed687e12 --- /dev/null +++ b/pytorch/shared/count_guided_candidates.py @@ -0,0 +1,49 @@ +"""文字ラベルの経路と、原文から推定した項目数で抽出候補を比較する。""" +from collections import Counter + +import numpy as np +import torch + +from shared.bibform_trial import FIELDS +from 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) diff --git a/pytorch/shared/count_guided_predictor.py b/pytorch/shared/count_guided_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc93a485cddcd82e578752e77aa362e203dd650 --- /dev/null +++ b/pytorch/shared/count_guided_predictor.py @@ -0,0 +1,81 @@ +"""文字経路の得点を保ち、学習した項目数で原文だけの抽出候補を選ぶ。""" +from copy import deepcopy + +import numpy as np +import torch + +from shared.bibform_trial import FIELDS,signature +from shared.count_guided_candidates import count_direction,count_vector,decode_candidates +from shared.span_tagger import OUTER_NAMES +from 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=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,:]best[parent] and total-original[parent]>self.minimum_gain: + best[parent]=total;selected[parent]=row + return selected diff --git a/pytorch/shared/csl_spans.py b/pytorch/shared/csl_spans.py new file mode 100644 index 0000000000000000000000000000000000000000..c03b7fd871971065318fefdb413cf5ea8fa71791 --- /dev/null +++ b/pytorch/shared/csl_spans.py @@ -0,0 +1,116 @@ +"""CSLが出力した注釈から、表示された項目・人物・姓名の文字範囲を構成する。""" + +from html.parser import HTMLParser +from difflib import SequenceMatcher +import hashlib +import random +import re + +from shared.dataset_schema import RAW_FIELD_NAMES as FIELD_NAMES, stable_seed +from 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 startstart 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] 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] 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, result diff --git a/pytorch/shared/dataset_schema.py b/pytorch/shared/dataset_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..1dcb4e25ab95be3b8d2c6697a564876569138738 --- /dev/null +++ b/pytorch/shared/dataset_schema.py @@ -0,0 +1,128 @@ +"""引用文字列から見える情報と、収集メタデータを分離するデータ仕様。""" + +import hashlib +from copy import deepcopy +import random +import re +import 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<=aa 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["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 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,result diff --git a/pytorch/shared/date_qualifier.py b/pytorch/shared/date_qualifier.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7b8b0772b146260cde77f3223b766ef394ca13 --- /dev/null +++ b/pytorch/shared/date_qualifier.py @@ -0,0 +1,37 @@ +"""認識済みの日付へ隣接する説明語を、他の抽出範囲に重ならない場合だけ含める。""" + +from copy import deepcopy +from functools import lru_cache +import 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'(? 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 result diff --git a/pytorch/shared/doi_volume_prior.py b/pytorch/shared/doi_volume_prior.py new file mode 100644 index 0000000000000000000000000000000000000000..2782664d92b86eae4c5b5c89081b2b901c335290 --- /dev/null +++ b/pytorch/shared/doi_volume_prior.py @@ -0,0 +1,44 @@ +"""訓練書誌で確認したDOIの数値構造から、既知の巻と異なる年の誤分類を補助する。""" + +from copy import deepcopy +import 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'(? 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 result diff --git a/pytorch/shared/field_span_classifier.py b/pytorch/shared/field_span_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..134ff7031141bc5f621bd7b15309a884f2798cd8 --- /dev/null +++ b/pytorch/shared/field_span_classifier.py @@ -0,0 +1,132 @@ +"""固定した3補助モデルの文字表現から、候補範囲の項目種別と不採用を判定する。""" +from collections import Counter +from copy import deepcopy + +import numpy as np +import torch +from torch import nn + +from shared.bibform_trial import FIELDS,validate +from 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] 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] 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 + + diff --git a/pytorch/shared/frozen_character_features.py b/pytorch/shared/frozen_character_features.py new file mode 100644 index 0000000000000000000000000000000000000000..febf93cbda406f84df02a7d2be04bcd59b802b04 --- /dev/null +++ b/pytorch/shared/frozen_character_features.py @@ -0,0 +1,40 @@ +"""保存した抽出器の文字表現を取得し、範囲予測層へ渡す。原文だけを入力する。""" +import json +from pathlib import Path + +from safetensors.torch import load_file +import torch + +from shared.range_extraction import build_range_head,prediction_from_ranges +from 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] diff --git a/pytorch/shared/global_field_counts.py b/pytorch/shared/global_field_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..1f02fbadfe3c9a6d41f5c18d76cfc80f817bfc39 --- /dev/null +++ b/pytorch/shared/global_field_counts.py @@ -0,0 +1,51 @@ +"""原文から得た引用全体の表現で、表示項目の個数を予測する。""" +import torch +from torch import nn + +from shared.bibform_trial import FIELDS +from 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,:] 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 result diff --git a/pytorch/shared/kbest_viterbi.py b/pytorch/shared/kbest_viterbi.py new file mode 100644 index 0000000000000000000000000000000000000000..4114858235f8e641a4c69e274293656b90066ffa --- /dev/null +++ b/pytorch/shared/kbest_viterbi.py @@ -0,0 +1,38 @@ +"""Return the best distinct paths through a small first-order state lattice.""" +import torch +from 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_paths diff --git a/pytorch/shared/name_boundary_prior.py b/pytorch/shared/name_boundary_prior.py new file mode 100644 index 0000000000000000000000000000000000000000..4711e0750188be9dabe2d2f90abe3e885be36ccc --- /dev/null +++ b/pytorch/shared/name_boundary_prior.py @@ -0,0 +1,161 @@ +"""訓練資料の姓・名の頻度と文字連鎖から、既存の人物範囲内の区切りを補助する。""" + +from collections import Counter +from copy import deepcopy +from functools import lru_cache +import hashlib +import math +import re +import unicodedata + +import numpy as np + +from shared.dataset_schema import visible_value +from 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 result diff --git a/pytorch/shared/name_context_cnn.py b/pytorch/shared/name_context_cnn.py new file mode 100644 index 0000000000000000000000000000000000000000..36bb01db4f507f7118d9c161f95d8788a5928d11 --- /dev/null +++ b/pytorch/shared/name_context_cnn.py @@ -0,0 +1,136 @@ +"""原文の文字と文脈表現から、人物内の姓名ラベルを補正する小さなCNN。""" +import numpy as np +import torch +from torch import nn +from copy import deepcopy + +from shared.dataset_schema import visible_value +from 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=start)&(positions torch.Tensor: + valid=torch.arange(features.shape[1],device=features.device)[None,:] 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 result diff --git a/pytorch/shared/name_conventions.py b/pytorch/shared/name_conventions.py new file mode 100644 index 0000000000000000000000000000000000000000..c35446da20e8a445da17632369fd5016f74b1bbe --- /dev/null +++ b/pytorch/shared/name_conventions.py @@ -0,0 +1,37 @@ +"""明示的な大文字表記と既存の姓名方針だけから、人物内の部品を整える。""" +from copy import deepcopy +import re +from shared.dataset_revision import PARTICLE +from shared.dataset_schema import visible_value + + +def apply_name_conventions(text: str, prediction: dict, rules: list[str]) -> dict: + result = deepcopy(prediction) + for person in result['contributors']: + if person['kind'] != 'person' or set(person['name_parts']) != {'family', 'given'}: + continue + parts = person['name_parts'] + family, given = parts['family'], parts['given'] + f, g = text[family['start']:family['end']], text[given['start']:given['end']] + if ('uppercase_surname' in rules and re.fullmatch(r'[A-Za-zÀ-ÖØ-öø-ÿ]+', f) + and re.fullmatch(r'[A-ZÀ-ÖØ-Þ]{3,}', g) and any(char.islower() for char in f)): + parts['family'], parts['given'] = given, family + continue + if 'surname_particle' not in rules or given['end'] > family['start']: + continue + if text[given['end']:family['start']].strip(): + continue + # 元の注釈方針と同じ、独立した小文字の前置詞だけを姓へ移す。 + match = PARTICLE.fullmatch(' '.join(g.split())) + if match is None: + continue + suffix = re.search(r'\s+'.join(re.escape(word) for word in match[2].split()) + r'\s*$', g) + if suffix is None: + continue + new_end = given['start'] + suffix.start() + while new_end > given['start'] and text[new_end - 1].isspace(): + new_end -= 1 + new_start = given['start'] + suffix.start() + given.update(end=new_end, value=visible_value(text[given['start']:new_end], 'given')) + family.update(start=new_start, value=visible_value(text[new_start:family['end']], 'family')) + return result diff --git a/pytorch/shared/package_resources.py b/pytorch/shared/package_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..79312b990ad83a6806f4726cb0906e9fa294b4d5 --- /dev/null +++ b/pytorch/shared/package_resources.py @@ -0,0 +1,71 @@ +"""推論用のJSON・トークナイザ資源を可逆圧縮し、使用時に一時配置する。""" +from compression import zstd +import hashlib +import io +import json +from pathlib import Path, PurePosixPath +import tarfile +import tempfile + + +def compress_resources(package: Path, additional_files: list[Path] | None = None) -> dict: + files = [path for path in package.rglob('*') if path.is_file() and path.suffix in {'.json', '.model'}] + for path in additional_files or []: + assert path.is_file() and path.is_relative_to(package) + if path not in files: + files.append(path) + assert files and not (package/'runtime_resources.json').exists() + contents = {str(path.relative_to(package)): path.read_bytes() for path in sorted(files)} + stream = io.BytesIO() + with tarfile.open(fileobj=stream, mode='w') as archive: + for name, content in contents.items(): + info = tarfile.TarInfo(name); info.size = len(content) + archive.addfile(info, io.BytesIO(content)) + compressed = zstd.compress(stream.getvalue(), level=9) + (package/'runtime_resources.tar.zst').write_bytes(compressed) + manifest = {'format': 'bibform-runtime-resources/1', 'archive_sha256': hashlib.sha256(compressed).hexdigest(), + 'files': {name: {'bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest()} + for name, content in contents.items()}} + (package/'runtime_resources.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2)+'\n') + for path in files: + path.unlink() + return {'original_resource_bytes': sum(len(content) for content in contents.values()), + 'compressed_archive_bytes': len(compressed), 'files': len(files)} + + +class RuntimeResources: + def __init__(self, package: Path) -> None: + package = package.absolute() + manifest = json.loads((package/'runtime_resources.json').read_text()) + if manifest['format'] != 'bibform-runtime-resources/1': + raise ValueError('unknown_resource_archive_format') + compressed = (package/'runtime_resources.tar.zst').read_bytes() + if hashlib.sha256(compressed).hexdigest() != manifest['archive_sha256']: + raise ValueError('resource_archive_hash_mismatch') + self.temporary = tempfile.TemporaryDirectory(prefix='bibform-runtime-resources-') + self.path = Path(self.temporary.name) + # Large weights stay in the package; selected small weights and static + # resources are restored byte for byte in the temporary tree. + for source in package.rglob('*'): + if source.is_file(): + target = self.path/source.relative_to(package) + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(source) + restored = set() + with tarfile.open(fileobj=io.BytesIO(zstd.decompress(compressed)), mode='r:') as archive: + for member in archive.getmembers(): + relative = PurePosixPath(member.name) + if (not member.isfile() or relative.is_absolute() or '..' in relative.parts + or member.name not in manifest['files'] or member.name in restored): + raise ValueError('invalid_resource_archive_member') + expected = manifest['files'][member.name] + content = archive.extractfile(member).read() + if len(content) != expected['bytes'] or hashlib.sha256(content).hexdigest() != expected['sha256']: + raise ValueError('resource_content_hash_mismatch') + destination = self.path/member.name + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open('xb') as stream: + stream.write(content) + restored.add(member.name) + if restored != set(manifest['files']): + raise ValueError('incomplete_resource_archive') diff --git a/pytorch/shared/range_extraction.py b/pytorch/shared/range_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..074cd18e6de5541c7a50cd95715b79bddead76c3 --- /dev/null +++ b/pytorch/shared/range_extraction.py @@ -0,0 +1,296 @@ +"""原文の文字表現から範囲を直接予測する4方式。辞書や書式情報を使わない。""" +import math + +import numpy as np +import torch +from torch import Tensor, nn +from torch.nn import functional as F + +from shared.dataset_schema import FIELD_NAMES, validate_target, visible_value + +RANGE_TYPES=(*FIELD_NAMES,'person','organization','family','given') + + +def gold_ranges(target: dict) -> list[tuple[int,int,int]]: + result=[(RANGE_TYPES.index(f['label']),f['start'],f['end']-1) for f in target['fields']] + for person in target['contributors']: + result.append((RANGE_TYPES.index(person['kind']),person['start'],person['end']-1)) + result.extend((RANGE_TYPES.index(k),v['start'],v['end']-1) for k,v in person['name_parts'].items()) + return sorted(result,key=lambda r:(r[1],-r[2],r[0])) + + +def position_features(length: int,width: int,device: torch.device) -> Tensor: + positions=torch.arange(length,device=device).float()[:,None] + frequency=torch.exp(torch.arange(0,width,2,device=device).float()*(-math.log(10000.)/width)) + result=torch.zeros(length,width,device=device) + result[:,0::2]=(positions*frequency).sin();result[:,1::2]=(positions*frequency).cos() + return result + + +def assignment(cost: np.ndarray) -> list[tuple[int,int]]: + """各正解行を異なる予測列へ対応付ける最小費用割当。行数は列数以下。""" + rows,columns=cost.shape + if rows>columns:raise ValueError('not_enough_prediction_slots') + u=np.zeros(rows+1);v=np.zeros(columns+1);p=np.zeros(columns+1,dtype=int);way=np.zeros(columns+1,dtype=int) + for i in range(1,rows+1): + p[0]=i;j0=0;minimum=np.full(columns+1,np.inf);used=np.zeros(columns+1,dtype=bool) + while True: + used[j0]=True;i0=p[j0] + values=cost[i0-1]-u[i0]-v[1:] + better=(values None: + super().__init__();self.mode=mode + self.norm=nn.LayerNorm(input_width) + self.start=nn.Linear(input_width,64);self.end=nn.Linear(input_width,64) + self.pair=nn.Parameter(torch.empty(len(RANGE_TYPES),65,65));nn.init.normal_(self.pair,std=.02) + self.bias=nn.Parameter(torch.full((len(RANGE_TYPES),),-2.)) + if mode=='query': + self.memory=nn.Linear(input_width,128) + self.queries=nn.Parameter(torch.randn(len(RANGE_TYPES),128)*.02) + self.attention=nn.MultiheadAttention(128,4,batch_first=True) + self.query_start=nn.Linear(128,64);self.query_end=nn.Linear(128,64) + + def forward(self,features: Tensor,lengths: Tensor) -> Tensor: + x=self.norm(features);a=F.gelu(self.start(x));b=F.gelu(self.end(x)) + if self.mode=='query': + memory=self.memory(x);query=self.queries.unsqueeze(0).expand(len(x),-1,-1) + mask=torch.arange(x.shape[1],device=x.device)[None,:]>=lengths[:,None] + query=query+self.attention(query,memory,memory,key_padding_mask=mask,need_weights=False)[0] + left=torch.einsum('blh,bch->bcl',a,self.query_start(query))/8 + right=torch.einsum('blh,bch->bcl',b,self.query_end(query))/8 + a=F.pad(a,(0,1),value=1);b=F.pad(b,(0,1),value=1) + scores=torch.einsum('blh,chd,bmd->bclm',a,self.pair,b)/8+self.bias[None,:,None,None] + if self.mode=='query':scores=scores+left[:,:,:,None]+right[:,:,None,:] + positions=torch.arange(x.shape[1],device=x.device) + valid=(positions[None,:] Tensor: + scores=self(features,lengths) + positive=torch.zeros_like(scores,dtype=torch.bool) + for i,target in enumerate(targets): + for label,start,end in gold_ranges(target):positive[i,label,start,end]=True + positives=F.softplus(-scores[positive]).mean() + negatives=scores.masked_fill(positive,-torch.inf).flatten(1) + hard=negatives.topk(min(256,negatives.shape[1]),dim=1).values + return positives+F.softplus(hard).mean() + + def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: + scores=self(features,lengths);result=[] + for values in scores: + indices=(values>threshold).nonzero() + selected=values[indices[:,0],indices[:,1],indices[:,2]] + result.append([(int(c),int(a),int(b)+1,float(s)-threshold) for (c,a,b),s in zip(indices.cpu().tolist(),selected.cpu().tolist(),strict=True)]) + return result + + +class SetRangeHead(nn.Module): + def __init__(self,input_width: int) -> None: + super().__init__() + self.memory=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,128)) + self.queries=nn.Embedding(256,128) + layer=nn.TransformerDecoderLayer(128,4,256,dropout=.1,batch_first=True) + self.decoder=nn.TransformerDecoder(layer,2) + self.types=nn.Linear(128,len(RANGE_TYPES)+1) + self.start=nn.Linear(128,128);self.end=nn.Linear(128,128) + + def forward(self,features: Tensor,lengths: Tensor) -> tuple[Tensor,Tensor,Tensor]: + memory=self.memory(features);length=memory.shape[1] + memory=memory+position_features(length,128,memory.device)[None,:,:] + # 1文字の外側項目と姓名が重なる最密な場合にも足りる枠数を確保する。 + slots=max(64,2*length) + indices=torch.arange(slots,device=memory.device) + query=self.queries(indices%256)+position_features(slots,128,memory.device) + query=query.unsqueeze(0).expand(len(memory),-1,-1) + mask=torch.arange(length,device=memory.device)[None,:]>=lengths[:,None] + query_mask=indices[None,:]>=torch.maximum(lengths*2,torch.full_like(lengths,64))[:,None] + decoded=self.decoder(query,memory,memory_key_padding_mask=mask,tgt_key_padding_mask=query_mask) + start=torch.einsum('bqh,blh->bql',self.start(decoded),memory)/math.sqrt(128) + end=torch.einsum('bqh,blh->bql',self.end(decoded),memory)/math.sqrt(128) + return self.types(decoded),start.masked_fill(mask[:,None,:],-torch.inf),end.masked_fill(mask[:,None,:],-torch.inf) + + def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: + types,start,end=self(features,lengths);type_gold=torch.full(types.shape[:2],len(RANGE_TYPES),device=types.device,dtype=torch.long) + slots=torch.maximum(lengths*2,torch.full_like(lengths,64)) + type_gold.masked_fill_(torch.arange(types.shape[1],device=types.device)[None,:]>=slots[:,None],-100) + position_losses=[] + for i,target in enumerate(targets): + gold=torch.tensor(gold_ranges(target),device=types.device,dtype=torch.long) + count=int(slots[i]) + cost=-types[i,:count].softmax(-1)[:,gold[:,0]].T-1.5*(start[i,:count].log_softmax(-1)[:,gold[:,1]].T+end[i,:count].log_softmax(-1)[:,gold[:,2]].T) + matched=assignment(cost.detach().cpu().numpy()) + rows=torch.tensor([a for a,b in matched],device=types.device);columns=torch.tensor([b for a,b in matched],device=types.device) + type_gold[i,columns]=gold[rows,0] + position_losses.append(F.cross_entropy(start[i,columns],gold[rows,1])+F.cross_entropy(end[i,columns],gold[rows,2])) + weights=torch.ones(len(RANGE_TYPES)+1,device=types.device);weights[-1]=.05 + return F.cross_entropy(types.transpose(1,2),type_gold,weight=weights)+torch.stack(position_losses).mean() + + def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: + types,start,end=self(features,lengths);result=[] + for i in range(len(features)): + count=max(64,2*int(lengths[i])) + score,label=types[i,:count,:-1].max(-1);score=score-types[i,:count,-1] + begins=start[i,:count].argmax(-1) + positions=torch.arange(end.shape[-1],device=end.device) + ends=end[i,:count].masked_fill(positions[None,:]threshold).nonzero().flatten() + result.append([(int(label[j]),int(begins[j]),int(ends[j])+1,float(score[j])-threshold) for j in keep.cpu().tolist()]) + return result + + +class PointerRangeHead(nn.Module): + def __init__(self,input_width: int) -> None: + super().__init__();self.memory=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,128)) + self.types=nn.Embedding(len(RANGE_TYPES)+2,128);self.recurrent=nn.GRU(128,128,batch_first=True) + self.type_head=nn.Linear(128,len(RANGE_TYPES)+1);self.pointer=nn.Linear(128,128) + self.initial=nn.Linear(128,128) + + def encoded(self,features: Tensor,lengths: Tensor) -> tuple[Tensor,Tensor,Tensor]: + memory=self.memory(features)+position_features(features.shape[1],128,features.device)[None,:,:] + mask=torch.arange(features.shape[1],device=features.device)[None,:]>=lengths[:,None] + pooled=(memory*~mask[:,:,None]).sum(1)/lengths[:,None] + return memory,mask,torch.tanh(self.initial(pooled))[None,:,:] + + def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: + memory,mask,initial=self.encoded(features,lengths) + sequences=[[v for triple in gold_ranges(target) for v in triple]+[len(RANGE_TYPES)] for target in targets] + count=max(map(len,sequences));batch=len(targets) + inputs=memory.new_zeros(batch,count,128);inputs[:,0]=self.types.weight[len(RANGE_TYPES)+1] + type_gold=torch.full((batch,count),-100,device=memory.device,dtype=torch.long) + point_gold=torch.full_like(type_gold,-100) + for i,sequence in enumerate(sequences): + for t,value in enumerate(sequence): + if t%3==0:type_gold[i,t]=value + else:point_gold[i,t]=value + if t+1btl',self.pointer(hidden),memory)/math.sqrt(128) + points=points.masked_fill(mask[:,None,:],-torch.inf) + return F.cross_entropy(types.transpose(1,2),type_gold)+F.cross_entropy(points.transpose(1,2),point_gold) + + def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: + result=[] + # 各引用の終了記号で止める。上限到達は明示的な出力失敗として返す。 + for i in range(len(features)): + length=int(lengths[i]);memory,mask,state=self.encoded(features[i:i+1,:length],lengths[i:i+1]) + value=self.types.weight[len(RANGE_TYPES)+1][None,None,:];spans=[];ended=False + for _ in range(2*length+1): + hidden,state=self.recurrent(value,state);logits=self.type_head(hidden)[0,0] + label=int(logits.argmax()) + if label==len(RANGE_TYPES):ended=True;break + confidence=float(logits[label]-logits[-1]);value=self.types.weight[label][None,None,:] + hidden,state=self.recurrent(value,state) + start=int((self.pointer(hidden)@memory.transpose(1,2)).argmax(-1)[0,0]);value=memory[:,start:start+1] + hidden,state=self.recurrent(value,state) + logits_end=(self.pointer(hidden)@memory.transpose(1,2))[0,0] + logits_end[:start]=-torch.inf;end=int(logits_end.argmax()) + item=(label,start,end+1,max(.001,confidence-threshold)) + if confidence>threshold:spans.append(item) + value=memory[:,end:end+1] + if len(spans)>1 and spans[-1][:3] in [s[:3] for s in spans[:-1]]:break + result.append(spans if ended else []) + return result + + + +class BIORangeHead(nn.Module): + needs_text=True + + def __init__(self,input_width: int) -> None: + super().__init__() + self.features=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,192),nn.GELU()) + self.outer=nn.Linear(192,31);self.names=nn.Linear(192,5) + + def forward(self,features: Tensor) -> list[Tensor]: + hidden=self.features(features) + return [self.outer(hidden),self.names(hidden)] + + def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: + from shared.dataset_schema import bio_labels + from shared.span_tagger import OUTER_NAMES,NAME_NAMES + gold=torch.full((len(targets),2,features.shape[1]),-100,device=features.device,dtype=torch.long) + for i,target in enumerate(targets): + outer=[(f['label'],f['start'],f['end']) for f in target['fields']]+[(p['kind'],p['start'],p['end']) for p in target['contributors']] + names=[(k,v['start'],v['end']) for p in target['contributors'] for k,v in p['name_parts'].items()] + gold[i,0,:int(lengths[i])]=torch.tensor(bio_labels(int(lengths[i]),outer,OUTER_NAMES),device=features.device) + gold[i,1,:int(lengths[i])]=torch.tensor(bio_labels(int(lengths[i]),names,NAME_NAMES),device=features.device) + scores=self(features) + return sum(F.cross_entropy(score.transpose(1,2),gold[:,i]) for i,score in enumerate(scores)) + + def extract(self,features: Tensor,lengths: Tensor,threshold: float,texts: list[str]) -> list[list[tuple[int,int,int,float]]]: + from shared.inference_strategies import structural_predictions + from shared.span_tagger import EncodedCitation + rows=[EncodedCitation(str(i),text,[0],[],[],[],None) for i,text in enumerate(texts)] + predictions=structural_predictions(self(features),rows,1.,{'structure':'single_title'}) + result=[] + for prediction in predictions: + spans=[(RANGE_TYPES.index(f['label']),f['start'],f['end'],1.) for f in prediction['fields']] + for person in prediction['contributors']: + spans.append((RANGE_TYPES.index(person['kind']),person['start'],person['end'],1.)) + spans.extend((RANGE_TYPES.index(k),v['start'],v['end'],1.) for k,v in person['name_parts'].items()) + result.append(spans) + return result + + +def build_range_head(architecture: str,input_width: int) -> nn.Module: + if architecture in ('span','query'):return DenseRangeHead(input_width,architecture) + if architecture=='bio':return BIORangeHead(input_width) + if architecture=='set':return SetRangeHead(input_width) + if architecture=='pointer':return PointerRangeHead(input_width) + raise ValueError('unknown_range_architecture') + + +def prediction_from_ranges(identifier: str,text: str,ranges: list[tuple[int,int,int,float]]) -> dict: + """得点の高い非重複項目を選び、人物内の姓名を元の文字位置で組み立てる。""" + unique={} + for label,start,end,score in ranges: + if 0<=start0: + key=(label,start,end);unique[key]=max(score,unique.get(key,-math.inf)) + outer=[(*key,score) for key,score in unique.items() if key[0]<15] + by_end={} + for candidate in outer:by_end.setdefault(candidate[2],[]).append(candidate) + length=len(text);best=np.full((2,length+1),-np.inf);best[0,0]=0;trace={} + for end in range(1,length+1): + for title in (0,1):best[title,end]=best[title,end-1];trace[title,end]=(title,end-1,None) + for label,start,stop,score in by_end.get(end,[]): + for title in (0,1): + if label==0 and title:continue + next_title=int(title or label==0);value=best[title,start]+score + if value>best[next_title,end]:best[next_title,end]=value;trace[next_title,end]=(title,start,(label,start,stop,score)) + title=int(best[1,length]>best[0,length]);end=length;selected=[] + while end: + previous,start,item=trace[title,end] + if item is not None:selected.append(item) + title,end=previous,start + result={'id':identifier,'fields':[],'contributors':[]} + for label,start,end,score in sorted(selected,key=lambda r:r[1]): + kind=RANGE_TYPES[label] + if label<13:result['fields'].append({'label':kind,'start':start,'end':end,'value':visible_value(text[start:end],kind)});continue + person={'kind':kind,'start':start,'end':end,'value':visible_value(text[start:end],'CONTRIBUTOR'),'name_parts':{}} + if kind=='person': + family=[None]+[(a,b,s) for (c,a,b),s in unique.items() if c==15 and start<=ag[0]:continue + value=(f[2] if f else 0)+(g[2] if g else 0) + if value>maximum:maximum=value;chosen=f,g + for name,part in zip(('family','given'),chosen,strict=True): + if part:person['name_parts'][name]={'start':part[0],'end':part[1],'value':visible_value(text[part[0]:part[1]],name)} + if not person['name_parts']:person['name_parts']['family']={'start':start,'end':end,'value':visible_value(text[start:end],'family')} + result['contributors'].append(person) + validate_target(text,result) + return result diff --git a/pytorch/shared/score_calibration.py b/pytorch/shared/score_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..b65b48f7e43f043d7fe0d9a4ce2da7d2a91b50f1 --- /dev/null +++ b/pytorch/shared/score_calibration.py @@ -0,0 +1,233 @@ +"""固定した4抽出モデルの得点と周辺文字から、小さな系列補正を学ぶ。""" + +import math + +import torch +from torch import nn +from torch.nn import functional as F + +from shared.dataset_schema import FIELD_NAMES, bio_labels + + +def context_features(features: torch.Tensor, lengths: torch.Tensor, scripts: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + position = torch.arange(features.shape[1], device=features.device)[None, :] + mask = position < lengths[:, None] + relative = position / (lengths[:, None] - 1).clamp_min(1) + size = torch.log1p(lengths.float())[:, None].expand_as(relative) / 5 + category = scripts[:, None].expand_as(relative).float() + result = torch.cat([features, relative[..., None], size[..., None], category[..., None]], dim=-1) + return result * mask[..., None], mask + + +class ScoreCalibrator(nn.Module): + def __init__(self, configuration: dict) -> None: + super().__init__() + self.configuration = configuration + self.vocabulary = configuration['vocabulary'] + self.outer_classes = configuration['outer_classes'] + classes = self.outer_classes + configuration['name_classes'] + width = configuration.get('width', 48) + embedding = configuration.get('embedding', 16) + self.embedding = nn.Embedding(len(self.vocabulary) + 2, embedding, padding_idx=0) + self.project = nn.Linear(4 * classes + 3 + embedding, width) + self.context1 = nn.Conv1d(width, width, 3, padding=1) + self.context2 = nn.Conv1d(width, width, 3, dilation=3, padding=3) + self.attention = None + if configuration.get('context') == 'attention': + layer = nn.TransformerEncoderLayer(width, 4, width * 2, .1, activation='gelu', batch_first=True) + self.attention = nn.TransformerEncoder(layer, 1, enable_nested_tensor=False) + self.dropout = nn.Dropout(.1) + self.head = nn.Linear(width, classes) + nn.init.zeros_(self.head.weight) + nn.init.zeros_(self.head.bias) + + def hidden(self, features: torch.Tensor, characters: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + value = torch.cat([features, self.embedding(characters)], dim=-1) + value = F.gelu(self.project(value)) * mask[..., None] + value = F.gelu(self.context1(value.transpose(1, 2))).transpose(1, 2) * mask[..., None] + value = F.gelu(self.context2(value.transpose(1, 2))).transpose(1, 2) * mask[..., None] + if self.attention is not None: + value = self.attention(value, src_key_padding_mask=~mask) * mask[..., None] + return value + + def forward(self, features: torch.Tensor, characters: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + value = self.hidden(features, characters, mask) + correction = self.configuration.get('max_delta', 2.) * torch.tanh(self.head(self.dropout(value))) + return correction * mask[..., None] + + def correct(self, outputs: list[list[torch.Tensor]], texts: list[str]) -> list[torch.Tensor]: + from shared.span_tagger import citation_script_group + device = outputs[0][0].device + features = torch.cat([F.log_softmax(value.float(), dim=-1).clamp_min(-20) / 5 + for member in outputs for value in member], dim=-1) + lengths = torch.tensor([len(text) for text in texts], device=device) + scripts = torch.tensor([citation_script_group(text) for text in texts], device=device) + features, mask = context_features(features, lengths, scripts) + characters = torch.zeros(mask.shape, dtype=torch.long, device=device) + for index, text in enumerate(texts): + characters[index, :len(text)] = torch.tensor([self.vocabulary.get(char, 1) for char in text], device=device) + correction = self(features, characters, mask) + return [correction[..., :self.outer_classes], correction[..., self.outer_classes:]] + + def calibrate(self, outputs: list[list[torch.Tensor]], texts: list[str], baseline: list[torch.Tensor]) -> list[torch.Tensor]: + return [value + delta for value, delta in zip(baseline, self.correct(outputs, texts), strict=True)] + + +class DynamicMixtureCalibrator(ScoreCalibrator): + """文字の周辺に応じて頭ごとの混合比を変え、固定4モデルの凸結合を保つ。""" + + def __init__(self, configuration: dict) -> None: + super().__init__(configuration) + self.head = nn.Linear(configuration.get('width', 48), 8) + nn.init.zeros_(self.head.weight) + nn.init.zeros_(self.head.bias) + profiles = torch.tensor(configuration['base_profiles'], dtype=torch.float32) + self.register_buffer('profiles', profiles / profiles.sum(-1, keepdim=True)) + + def mixture_weights(self, gates: torch.Tensor, scripts: torch.Tensor) -> torch.Tensor: + base = self.profiles[scripts, None] + values = base * torch.exp(2 * torch.tanh(gates)) + return values / values.sum(-1, keepdim=True) + + def forward(self, features: torch.Tensor, characters: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + hidden = self.hidden(features, characters, mask) + gates = self.head(self.dropout(hidden)).reshape(*features.shape[:2], 2, 4) + scripts = features[:, 0, -1].long() + delta = self.mixture_weights(gates, scripts) - self.profiles[scripts, None] + classes = self.outer_classes + self.configuration['name_classes'] + members = features[..., :4 * classes].reshape(*features.shape[:2], 4, classes) * 5 + outer = (members[..., :self.outer_classes] * delta[:, :, 0, :, None]).sum(2) + names = (members[..., self.outer_classes:] * delta[:, :, 1, :, None]).sum(2) + return torch.cat([outer, names], dim=-1) * mask[..., None] + + +class LabelScoreCalibrator(nn.Module): + """項目のB/Iを同じ係数で扱い、既存得点からの差だけを学ぶ。""" + def __init__(self, configuration: dict) -> None: + super().__init__() + self.configuration = configuration + self.configuration = configuration + self.outer_classes = configuration['outer_classes'] + self.name_classes = configuration['name_classes'] + outer_groups = (self.outer_classes + 1) // 2 + name_groups = (self.name_classes + 1) // 2 + profiles = torch.tensor(configuration['base_profiles'], dtype=torch.float32) + profiles = profiles / profiles.sum(-1, keepdim=True) + base = torch.cat([profiles[:, 0, :, None].expand(-1, -1, outer_groups), + profiles[:, 1, :, None].expand(-1, -1, name_groups)], dim=-1) + self.register_buffer('base', base) + groups = [0, *[index for index in range(1, outer_groups) for _ in range(2)]] + groups += [outer_groups, *[outer_groups + index for index in range(1, name_groups) for _ in range(2)]] + self.register_buffer('groups', torch.tensor(groups, dtype=torch.long)) + self.weights = nn.Parameter(torch.zeros_like(base)) + self.bias = nn.Parameter(torch.zeros(2, outer_groups + name_groups)) + + def differences(self) -> tuple[torch.Tensor, torch.Tensor]: + adjusted = (self.base + .25 * torch.tanh(self.weights)).clamp_min(0) + difference = adjusted / adjusted.sum(1, keepdim=True) - self.base / self.base.sum(1, keepdim=True) + return difference[..., self.groups], .5 * torch.tanh(self.bias)[..., self.groups] + + def mix(self, features: torch.Tensor, baseline: list[torch.Tensor]) -> list[torch.Tensor]: + classes = self.outer_classes + self.name_classes + scripts = features[:, 0, -1].long() + member = features[..., :4 * classes].reshape(*features.shape[:2], 4, classes) * 5 + weights, bias = self.differences() + correction = (member * weights[scripts, None]).sum(2) + bias[scripts, None] + return [baseline[0] + correction[..., :self.outer_classes], baseline[1] + correction[..., self.outer_classes:]] + + def penalty(self) -> torch.Tensor: + weights, bias = self.differences() + return weights.square().mean() + bias.square().mean() + + def calibrate(self, outputs: list[list[torch.Tensor]], texts: list[str], baseline: list[torch.Tensor]) -> list[torch.Tensor]: + from shared.span_tagger import citation_script_group + features = torch.cat([F.log_softmax(value.float(), dim=-1).clamp_min(-20) / 5 + for member in outputs for value in member], dim=-1) + device = features.device + lengths = torch.tensor([len(text) for text in texts], device=device) + scripts = torch.tensor([citation_script_group(text) for text in texts], device=device) + features, _ = context_features(features, lengths, scripts) + return self.mix(features, baseline) + + +def span_contrasts(text: str, target: dict, outer_names: tuple[str, ...], name_names: tuple[str, ...], limit: int = 12) -> list[list[tuple[int, int, int, int]]]: + """正解を変更せず、範囲をずらした合法なBIO候補との差だけを返す。""" + outer = [(row['label'], row['start'], row['end']) for row in target['fields']] + outer += [(row['kind'], row['start'], row['end']) for row in target['contributors']] + names = [(part, span['start'], span['end']) for person in target['contributors'] for part, span in person['name_parts'].items()] + originals = [bio_labels(len(text), spans, labels) for spans, labels in ((outer, outer_names), (names, name_names))] + candidates = [] + for layer, spans in enumerate((outer, names)): + labels = outer_names if layer == 0 else name_names + for index, (label, start, end) in enumerate(spans): + if layer == 0 and label not in FIELD_NAMES: + continue + for side, step in (('end', 1), ('end', -1), ('start', 1), ('start', -1)): + a, b = (start + step, end) if side == 'start' else (start, end + step) + if not 0 <= a < b <= len(text): + continue + if layer == 1 and not any(p['kind'] == 'person' and p['start'] <= a < b <= p['end'] for p in target['contributors']): + continue + changed = list(spans) + changed[index] = (label, a, b) + try: + tags = bio_labels(len(text), changed, labels) + except ValueError: + continue + difference = [(layer, position, gold, wrong) for position, (gold, wrong) in enumerate(zip(originals[layer], tags)) if gold != wrong] + if difference: + candidates.append(difference) + # 連続した姓名は、空白を作る候補に加えて、姓と名の境界自体を動かす。 + for person in target['contributors']: + parts = sorted(person['name_parts'].items(), key=lambda item: item[1]['start']) + if len(parts) != 2 or parts[0][1]['end'] != parts[1][1]['start']: + continue + for step in (-1, 1): + left, right = parts + boundary = left[1]['end'] + step + if not left[1]['start'] < boundary < right[1]['end']: + continue + changed = [(label, a, b) for label, a, b in names + if (label, a, b) not in [(left[0], left[1]['start'], left[1]['end']), (right[0], right[1]['start'], right[1]['end'])]] + changed += [(left[0], left[1]['start'], boundary), (right[0], boundary, right[1]['end'])] + tags = bio_labels(len(text), changed, name_names) + candidates.insert(0, [(1, position, gold, wrong) for position, (gold, wrong) in enumerate(zip(originals[1], tags)) if gold != wrong]) + unique = [] + for candidate in candidates: + if candidate not in unique: + unique.append(candidate) + # 外側項目だけで枠を埋めないよう、姓名と一般項目を交互に残す。 + outer_groups = {} + for row in unique: + if row[0][0] == 0: + tag = row[0][2] or row[0][3] + outer_groups.setdefault(outer_names[(tag - 1) // 2], []).append(row) + outer_pool = [] + for index in range(max((len(rows) for rows in outer_groups.values()), default=0)): + for rows in outer_groups.values(): + if index < len(rows): + outer_pool.append(rows[index]) + pools = [outer_pool, [row for row in unique if row[0][0] == 1]] + result = [] + for index in range(max(map(len, pools), default=0)): + for pool in pools: + if index < len(pool): + result.append(pool[index]) + return result[:limit] + + +def contrastive_loss(scores: list[torch.Tensor], contrasts: list[list[list[tuple[int, int, int, int]]]]) -> torch.Tensor: + entries, sizes = [], [] + for row, candidates in enumerate(contrasts): + for candidate in candidates: + for layer, position, correct, wrong in candidate: + offset = scores[0].shape[-1] if layer else 0 + entries.append((row, position, correct + offset, wrong + offset, len(sizes))) + sizes.append(math.sqrt(len(candidate))) + if not entries: + return scores[0].sum() * 0 + indexes = torch.tensor(entries, dtype=torch.long, device=scores[0].device) + joined = torch.cat(scores, dim=-1) + difference = joined[indexes[:, 0], indexes[:, 1], indexes[:, 2]] - joined[indexes[:, 0], indexes[:, 1], indexes[:, 3]] + totals = torch.zeros(len(sizes), device=joined.device).scatter_add_(0, indexes[:, 4], difference) + return F.softplus(1 - totals / torch.tensor(sizes, device=joined.device)).mean() diff --git a/pytorch/shared/span_tagger.py b/pytorch/shared/span_tagger.py new file mode 100644 index 0000000000000000000000000000000000000000..91754d29e45cbd94e393afa0163fc81179682039 --- /dev/null +++ b/pytorch/shared/span_tagger.py @@ -0,0 +1,785 @@ +"""文字単位の書誌抽出。推論は引用テキストだけを受け取る。""" + +from dataclasses import dataclass +from copy import deepcopy +from functools import lru_cache +import json +import gzip +from compression import zstd +from pathlib import Path + +import torch +from torch import Tensor, nn +from transformers import AutoConfig, AutoModel, AutoTokenizer, PreTrainedTokenizerFast + +from shared.dataset_schema import FIELD_NAMES, bio_labels, validate_target, visible_value + +OUTER_NAMES = (*FIELD_NAMES, 'person', 'organization') +NAME_NAMES = ('family', 'given') +LAYERS = (OUTER_NAMES, NAME_NAMES) + + +@dataclass +class EncodedCitation: + identifier: str + text: str + input_ids: list[int] + character_tokens: list[int] + character_ids: list[int] + token_positions: list[int] + labels: list[list[int]] | None + + +def encode_citations(inputs: list[dict], tokenizer: PreTrainedTokenizerFast, + vocabulary: dict[str, int], targets: list[dict] | None = None) -> list[EncodedCitation]: + """サブワードの文字範囲を対応付ける。長文を黙って切り捨てない。""" + if targets is not None and [r['id'] for r in inputs] != [r['id'] for r in targets]: + raise ValueError('input_target_id_mismatch') + rows = [] + for begin in range(0, len(inputs), 512): + chunk = inputs[begin:begin + 512] + tokens = tokenizer([r['text'] for r in chunk], return_offsets_mapping=True, truncation=False) + for index, row in enumerate(chunk): + text = row['text'] + if not text: + raise ValueError(f"empty_input_text:{row['id']}") + mapping = [0] * len(text) + positions = [0] * len(text) + for token_index, (start, end) in enumerate(tokens['offset_mapping'][index]): + for position in range(start, end): + mapping[position] = token_index + positions[position] = min(position - start + 1, 31) + # SentencePieceが落とす空白も、直前の文脈を用いて文字として予測する。 + previous = 0 + for position in range(len(text)): + if mapping[position]: + previous = mapping[position] + else: + mapping[position] = previous + labels = None + if targets is not None: + gold = targets[begin + index] + validate_target(text, gold) + outer = [(f['label'], f['start'], f['end']) for f in gold['fields']] + outer += [(p['kind'], p['start'], p['end']) for p in gold['contributors']] + names = [(part, span['start'], span['end']) for p in gold['contributors'] + for part, span in p['name_parts'].items()] + labels = [bio_labels(len(text), outer, OUTER_NAMES), bio_labels(len(text), names, NAME_NAMES)] + rows.append(EncodedCitation(row['id'], text, tokens['input_ids'][index], mapping, + [vocabulary.get(c, 1) for c in text], positions, labels)) + return rows + + +def collate(rows: list[EncodedCitation], pad_token: int, device: str) -> dict[str, Tensor]: + batch = len(rows) + token_length = max(len(r.input_ids) for r in rows) + char_length = max(len(r.text) for r in rows) + 4 + tensors = { + 'input_ids': torch.full((batch, token_length), pad_token, dtype=torch.long), + 'attention_mask': torch.zeros((batch, token_length), dtype=torch.long), + 'character_tokens': torch.zeros((batch, char_length), dtype=torch.long), + 'character_ids': torch.zeros((batch, char_length), dtype=torch.long), + 'token_positions': torch.zeros((batch, char_length), dtype=torch.long), + 'character_mask': torch.zeros((batch, char_length), dtype=torch.bool), + } + if rows[0].labels is not None: + tensors['labels'] = torch.full((batch, 2, char_length), -100, dtype=torch.long) + for index, row in enumerate(rows): + nt, nc = len(row.input_ids), len(row.text) + tensors['input_ids'][index, :nt] = torch.tensor(row.input_ids) + tensors['attention_mask'][index, :nt] = 1 + for key in ('character_tokens', 'character_ids', 'token_positions'): + tensors[key][index, :nc] = torch.tensor(getattr(row, key)) + tensors['character_mask'][index, :nc] = True + if row.labels is not None: + tensors['labels'][index, :, :nc] = torch.tensor(row.labels) + return {key: value.to(device) for key, value in tensors.items()} + + +def retained_vocabulary_ids(config: dict) -> list[int] | None: + if 'retained_token_ids' in config: + return config['retained_token_ids'] + if 'removed_token_ids' in config: + removed = set(config['removed_token_ids']) + return [index for index in range(config['original_vocab_size']) if index not in removed] + return None + + +class CharacterTagger(nn.Module): + def __init__(self, config: dict, pretrained: str | None = None) -> None: + super().__init__() + self.training_lexicon = None + self.decoder = config.get('decoder', 'independent') + self.name_weight = config.get('name_weight', 1.) + encoder_config = AutoConfig.for_model(**config['encoder']) + if encoder_config.model_type == 'modernbert': + # ModernBertConfig.to_dictは実行設定を落とすため、CPU/GPUとも既定で非コンパイルにする。 + encoder_config.reference_compile = config['encoder'].get('reference_compile', False) + encoder_options = ({'add_pooling_layer': config.get('use_pooler', True)} + if encoder_config.model_type in ('bert', 'roberta', 'xlm-roberta') else {}) + if pretrained and encoder_config.model_type == 'modernbert': + encoder_options['reference_compile'] = encoder_config.reference_compile + self.encoder = (AutoModel.from_pretrained(pretrained, **encoder_options) + if pretrained else AutoModel.from_config(encoder_config, **encoder_options)) + self.register_buffer('token_remap', None, persistent=False) + retained_ids = retained_vocabulary_ids(config) + if retained_ids is not None: + retained = torch.tensor(retained_ids, dtype=torch.long) + unknown = retained_ids.index(config['original_unk_token_id']) + remap = torch.full((config['original_vocab_size'],), unknown, dtype=torch.long) + remap[retained] = torch.arange(len(retained)) + self.token_remap = remap + if pretrained: + original = self.encoder.get_input_embeddings() + weights = original.weight.detach()[retained].clone() + self.encoder.set_input_embeddings(nn.Embedding.from_pretrained( + weights, freeze=False, padding_idx=encoder_config.pad_token_id)) + self.encoder.config.vocab_size = len(retained) + width = config.get('width', 192) + self.characters = nn.Embedding(config['vocabulary_size'], 64, padding_idx=0) + with torch.no_grad(): + self.characters.weight[1].zero_() + self.character_dropout = config.get('character_dropout', 0.) + self.positions = nn.Embedding(32, 16, padding_idx=0) + self.projection = nn.Linear(encoder_config.hidden_size + 80, width) + self.convolutions = nn.ModuleList([nn.Conv1d(width, width, 5, padding=2) for _ in range(2)]) + self.norms = nn.ModuleList([nn.LayerNorm(width) for _ in range(2)]) + self.recurrent = nn.LSTM(width, width // 2, batch_first=True, bidirectional=True) + self.recurrent_projection = nn.Linear(width, width) + self.dropout = nn.Dropout(.1) + self.heads = nn.ModuleList([nn.Linear(width, 1 + 2 * len(names)) for names in LAYERS]) + self.outer_adapter = None + self.outer_adapter_max_delta = 8. + self.register_buffer('outer_adapter_rows', torch.empty(0, dtype=torch.long), persistent=False) + if config.get('outer_adapter'): + adapter = config['outer_adapter'] + rows = adapter['classes'] + if not rows or len(set(rows)) != len(rows) or any(not 0 <= i < self.heads[0].out_features for i in rows): + raise ValueError('invalid_outer_adapter_classes') + self.outer_adapter = nn.Linear(width, len(rows)) + nn.init.zeros_(self.outer_adapter.weight) + nn.init.zeros_(self.outer_adapter.bias) + self.outer_adapter_rows = torch.tensor(rows, dtype=torch.long) + self.outer_adapter_max_delta = adapter.get('max_delta', 8.) + self.global_projection = None + self.token_head = None + if config.get('global_context', False): + self.enable_global_context() + if config.get('token_auxiliary_weight', 0.) > 0: + self.enable_token_auxiliary() + + def enable_global_context(self) -> None: + if self.global_projection is None: + layer = nn.Linear(self.encoder.config.hidden_size, self.projection.out_features, + device=self.projection.weight.device, dtype=self.projection.weight.dtype) + nn.init.zeros_(layer.weight) + nn.init.zeros_(layer.bias) + self.global_projection = layer + + def enable_token_auxiliary(self) -> None: + if self.token_head is None: + layer = nn.Linear(self.encoder.config.hidden_size, len(OUTER_NAMES) + 1, + device=self.projection.weight.device, dtype=self.projection.weight.dtype) + nn.init.zeros_(layer.weight) + nn.init.zeros_(layer.bias) + self.token_head = layer + + def forward(self, input_ids: Tensor, attention_mask: Tensor, character_tokens: Tensor, + character_ids: Tensor, token_positions: Tensor, character_mask: Tensor, + labels: Tensor | None = None) -> list[Tensor]: + if self.token_remap is not None: + input_ids = self.token_remap[input_ids] + if input_ids.shape[1] <= 512: + contextual = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state + else: + # 重複窓の文脈を平均し、切り捨てず元の文字位置で抽出する。 + contextual = None + lengths = attention_mask.sum(1) + counts = torch.zeros(input_ids.shape, device=input_ids.device) + for start in range(0, input_ids.shape[1], 384): + end = min(start + 512, input_ids.shape[1]) + # 前の窓で末尾へ達した引用を、別の引用の長さに合わせて再計算しない。 + previous_end = start + 128 if start else 0 + active = (lengths > previous_end).nonzero(as_tuple=True)[0] + if not active.numel(): + break + encoded = self.encoder(input_ids=input_ids[active, start:end], + attention_mask=attention_mask[active, start:end]).last_hidden_state + padded = torch.nn.functional.pad(encoded, (0, 0, start, input_ids.shape[1] - end)) + window = padded.new_zeros((*input_ids.shape, encoded.shape[-1])).index_copy(0, active, padded) + contextual = window if contextual is None else contextual + window + counts[active, start:end] += 1 + if end == input_ids.shape[1]: + break + if contextual is None: + raise ValueError('empty_token_sequence') + contextual = contextual / counts.clamp_min(1).unsqueeze(-1) + + token_contextual = contextual + global_features = None + if self.global_projection is not None: + pooled = (contextual * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(1).clamp_min(1).unsqueeze(-1) + global_features = self.global_projection(pooled) + if self.training and self.character_dropout > 0: + dropped = torch.rand_like(character_ids, dtype=torch.float32) < self.character_dropout + character_ids = character_ids.masked_fill(dropped & character_mask, 1) + contextual = contextual.gather(1, character_tokens.unsqueeze(-1).expand(-1, -1, contextual.shape[-1])) + features = torch.cat((contextual, self.characters(character_ids), self.positions(token_positions)), -1) + features = torch.nn.functional.gelu(self.projection(features)) + if global_features is not None: + features = features + global_features.unsqueeze(1) + mask = character_mask.unsqueeze(-1) + features = features * mask + for convolution, norm in zip(self.convolutions, self.norms): + hidden = torch.nn.functional.gelu(convolution(features.transpose(1, 2)).transpose(1, 2)) + features = norm(features + self.dropout(hidden)) * mask + # 固定の末尾余白を確保し、バッチの長さによる逆方向LSTMの差を防ぐ。 + with torch.autocast(device_type=features.device.type, enabled=False): + packed = nn.utils.rnn.pack_padded_sequence(features.float(), character_mask.sum(1).cpu(), + batch_first=True, enforce_sorted=False) + recurrent, _ = self.recurrent(packed) + recurrent, _ = nn.utils.rnn.pad_packed_sequence(recurrent, batch_first=True, + total_length=features.shape[1]) + features = features + self.recurrent_projection(recurrent.to(features.dtype)) + logits = [head(self.dropout(features)) for head in self.heads] + if self.outer_adapter is not None: + delta = self.outer_adapter(self.dropout(features)) + delta = self.outer_adapter_max_delta * torch.tanh(delta / self.outer_adapter_max_delta) + logits[0] = logits[0].index_add(-1, self.outer_adapter_rows, delta) + if self.token_head is not None: + logits.append(self.token_head(self.dropout(token_contextual))) + return logits + + + + + +def citation_script_group(text: str) -> int: + """引用文にCJK文字があるかを、収集時の言語情報を使わずに判定する。""" + return int(any(0x3040 <= ord(char) <= 0x30ff or 0x3400 <= ord(char) <= 0x9fff + or 0x20000 <= ord(char) <= 0x3134f for char in text)) + + +class EnsembleTagger(nn.Module): + """共通の文字位置で、各モデルの文字辞書を対応付けて系列の得点を平均する。""" + def __init__(self, members: list[CharacterTagger], configurations: list[dict], config: dict) -> None: + super().__init__() + self.members = nn.ModuleList(members) + self.configurations = configurations + self.member_tokenizers: list[PreTrainedTokenizerFast] | None = None + self.decoder = config.get('decoder', 'joint') + self.name_weight = config.get('name_weight', 1.) + self.training_lexicon = None + self.register_buffer('ensemble_weights', torch.tensor(config['ensemble_weights'], dtype=torch.float32), persistent=False) + script_weights = config.get('ensemble_script_weights') + self.register_buffer('ensemble_script_weights', torch.tensor(script_weights, dtype=torch.float32) + if script_weights is not None else None, persistent=False) + vocabulary = config['vocabulary'] + for index, member_config in enumerate(configurations): + remap = torch.ones(max(vocabulary.values(), default=1) + 1, dtype=torch.long) + remap[0] = 0 + for character, identifier in vocabulary.items(): + remap[identifier] = member_config['vocabulary'].get(character, 1) + self.register_buffer(f'character_remap_{index}', remap, persistent=False) + if len(members) != len(configurations) or self.ensemble_weights.shape != (2, len(members)): + raise ValueError('ensemble_member_count_mismatch') + if not torch.isfinite(self.ensemble_weights).all() or (self.ensemble_weights < 0).any() or (self.ensemble_weights.sum(1) <= 0).any(): + raise ValueError('invalid_ensemble_weights') + if self.ensemble_script_weights is not None: + weights = self.ensemble_script_weights + if weights.shape != (2, 2, len(members)) or not torch.isfinite(weights).all() or (weights < 0).any() or (weights.sum(2) <= 0).any(): + raise ValueError('invalid_ensemble_script_weights') + + def weights_for_rows(self, rows: list[EncodedCitation]) -> Tensor: + if self.ensemble_script_weights is None: + return self.ensemble_weights + categories = torch.tensor([citation_script_group(row.text) for row in rows], device=self.ensemble_weights.device) + return self.ensemble_script_weights[categories].permute(1, 2, 0) + + def member_outputs(self, **tensors: Tensor) -> list[list[Tensor]]: + if self.member_tokenizers is not None: + raise ValueError('separate_tokenizers_require_original_text_rows') + outputs = [] + for index, member in enumerate(self.members): + remap = getattr(self, f'character_remap_{index}') + batch = {**tensors, 'character_ids': remap[tensors['character_ids']]} + outputs.append(member(**batch)[:2]) + return outputs + + def member_text_outputs(self, rows: list[EncodedCitation], device: str) -> list[list[Tensor]]: + """異なる単語分割を、元の引用文の文字位置へそろえる。""" + if self.member_tokenizers is None: + raise ValueError('ensemble_has_no_separate_tokenizers') + inputs = [{'id': row.identifier, 'text': row.text} for row in rows] + outputs = [] + for member, config, tokenizer in zip(self.members, self.configurations, self.member_tokenizers, strict=True): + encoded = encode_citations(inputs, tokenizer, config['vocabulary']) + outputs.append(member(**collate(encoded, tokenizer.pad_token_id, device))[:2]) + return outputs + + def forward(self, **tensors: Tensor) -> list[Tensor]: + if self.ensemble_script_weights is not None: + raise ValueError('script_weights_require_original_text_rows') + outputs = self.member_outputs(**tensors) + return combine_ensemble_logits(outputs, self.ensemble_weights) + + +def combine_ensemble_logits(outputs: list[list[Tensor]], weights: Tensor) -> list[Tensor]: + weights = weights / weights.sum(1, keepdim=True) + return [sum(scores[layer].float() * (weights[layer, member] if weights.ndim == 2 + else weights[layer, member, :, None, None]) for member, scores in enumerate(outputs)) + for layer in range(2)] + + +def retain_encoder_layers(model: CharacterTagger, config: dict, retained: list[int]) -> dict: + """選んだ層の順序と重みを保ち、エンコーダーを同じ幅の浅い構成へ変える。""" + layers = model.encoder.encoder.layer + if not retained or retained != sorted(set(retained)) or retained[0] < 0 or retained[-1] >= len(layers): + raise ValueError('invalid_retained_encoder_layers') + updated = deepcopy(config) + updated['encoder']['num_hidden_layers'] = len(retained) + updated['retained_encoder_layers'] = retained + updated['original_encoder_depth'] = len(layers) + model.encoder.encoder.layer = nn.ModuleList([layers[index] for index in retained]) + model.encoder.config.num_hidden_layers = len(retained) + return updated + + +def token_kl_divergence(student: Tensor, teacher: Tensor, mask: Tensor, temperature: float) -> Tensor: + """正解のある文字だけで、教師の分布を固定して生徒へ渡す。""" + log_probability = torch.nn.functional.log_softmax(student.float() / temperature, dim=-1) + probability = torch.nn.functional.softmax(teacher.detach().float() / temperature, dim=-1) + losses = torch.nn.functional.kl_div(log_probability, probability, reduction='none').sum(-1) + return (losses * mask).sum() / mask.sum().clamp_min(1) * temperature ** 2 + + +def boundary_cross_entropy(logits: Tensor, targets: Tensor, weight: float) -> Tensor: + """範囲の始端・終端とその隣を重くし、重み総和で平均する。""" + if weight == 1: + return torch.nn.functional.cross_entropy(logits.transpose(1, 2), targets) + tags = targets.clamp_min(0) + classes = (tags + 1) // 2 + padded = torch.nn.functional.pad(classes, (1, 1)) + next_begin = torch.nn.functional.pad(tags[:, 1:] % 2 == 1, (0, 1)) + boundary = (tags % 2 == 1) | (classes != padded[:, :-2]) | (classes != padded[:, 2:]) | next_begin + weights = (targets >= 0).float() * (1 + (weight - 1) * boundary.float()) + losses = torch.nn.functional.cross_entropy(logits.transpose(1, 2), targets, reduction='none') + return (losses * weights).sum() / weights.sum().clamp_min(1) + + +def token_auxiliary_loss(logits: Tensor, batch: dict[str, Tensor]) -> Tensor: + """一つの項目に収まるサブワードだけで、エンコーダーの項目分類を補助する。""" + labels = batch['labels'][:, 0] + valid = (labels >= 0) & (batch['token_positions'] > 0) & batch['character_mask'] + classes = ((labels + 1) // 2).clamp_min(0) + one_hot = torch.nn.functional.one_hot(classes, len(OUTER_NAMES) + 1).float() * valid.unsqueeze(-1) + counts = logits.new_zeros(logits.shape, dtype=torch.float32) + indices = batch['character_tokens'].unsqueeze(-1).expand(-1, -1, counts.shape[-1]) + counts.scatter_add_(1, indices, one_hot) + eligible = (counts > 0).sum(-1) == 1 + if not eligible.any(): + return logits.sum() * 0 + targets = counts.argmax(-1).masked_fill(~eligible, -100) + return torch.nn.functional.cross_entropy(logits.transpose(1, 2), targets) + + + +def encoder_embedding_weight_key(model: CharacterTagger) -> str: + weight = model.encoder.get_input_embeddings().weight + return next(name for name, parameter in model.named_parameters() if parameter is weight) + + +def prune_saved_vocabulary(model: CharacterTagger, config: dict, retained: list[int], + unknown_id: int) -> tuple[CharacterTagger, dict]: + """学習済みの行を保って保存語彙を減らす。削除側が短ければ削除IDだけを記録する。""" + if retained_vocabulary_ids(config) is not None: + raise ValueError('model_already_has_pruned_vocabulary') + original_size = config['encoder']['vocab_size'] + if retained != sorted(set(retained)) or not retained or not 0 <= retained[0] <= retained[-1] < original_size: + raise ValueError('invalid_retained_vocabulary_ids') + if unknown_id not in retained or config['encoder']['pad_token_id'] not in retained: + raise ValueError('required_special_token_removed') + if retained.index(config['encoder']['pad_token_id']) != config['encoder']['pad_token_id']: + raise ValueError('pruning_would_change_padding_id') + new_config = deepcopy(config) + new_config['encoder']['vocab_size'] = len(retained) + new_config['original_vocab_size'] = original_size + new_config['original_unk_token_id'] = unknown_id + retained_set = set(retained) + removed = [index for index in range(original_size) if index not in retained_set] + if len(removed) < len(retained): + new_config['removed_token_ids'] = removed + else: + new_config['retained_token_ids'] = retained + pruned = CharacterTagger(new_config) + state = model.state_dict() + state[encoder_embedding_weight_key(model)] = model.encoder.get_input_embeddings().weight.detach()[retained].clone() + pruned.load_state_dict(state) + pruned.training_lexicon = model.training_lexicon + return pruned, new_config + + +def restore_full_vocabulary(model: CharacterTagger, config: dict, base: Path) -> tuple[CharacterTagger, dict]: + """学習済みの採用語彙と抽出層を保持し、未採用行を固定基盤から復元する。""" + retained_ids = retained_vocabulary_ids(config) + if retained_ids is None: + raise ValueError('model_does_not_have_pruned_vocabulary') + original = AutoConfig.from_pretrained(base, local_files_only=True).to_dict() + if original['vocab_size'] != config['original_vocab_size']: + raise ValueError('restored_base_vocabulary_mismatch') + for key in ('model_type', 'hidden_size', 'num_hidden_layers'): + if original[key] != config['encoder'][key]: + raise ValueError('restored_base_architecture_mismatch') + restored_config = deepcopy(config) + restored_config['encoder'] = original + for key in ('retained_token_ids', 'removed_token_ids', 'original_vocab_size', 'original_unk_token_id'): + restored_config.pop(key, None) + restored_config['restored_retained_vocabulary_size'] = len(retained_ids) + restored = CharacterTagger(restored_config, str(base)) + embedding_key = encoder_embedding_weight_key(model) + state = {key: value for key, value in model.state_dict().items() if key != embedding_key} + incompatible = restored.load_state_dict(state, strict=False) + if incompatible.missing_keys != [embedding_key] or incompatible.unexpected_keys: + raise ValueError('restored_model_state_mismatch') + with torch.no_grad(): + retained = torch.tensor(retained_ids, dtype=torch.long) + restored.encoder.get_input_embeddings().weight.index_copy_( + 0, retained, model.encoder.get_input_embeddings().weight.detach().cpu()) + restored.training_lexicon = model.training_lexicon + return restored, restored_config + + +def legal_transitions(names: tuple[str, ...], device: torch.device) -> Tensor: + size = 1 + 2 * len(names) + transitions = torch.zeros(size, size, device=device) + for destination in range(2, size, 2): + transitions[:, destination] = -10000 + transitions[destination - 1:destination + 1, destination] = 0 + return transitions + + +def viterbi_paths(emissions: Tensor, lengths: list[int], transitions: Tensor, + start_penalty: Tensor, end_penalty: Tensor) -> list[list[int]]: + # 小さい状態行列の逐次処理はCPUへまとめ、文字ごとのGPU同期を避ける。 + emissions, transitions = emissions.float().cpu(), transitions.cpu() + start_penalty, end_penalty = start_penalty.cpu(), end_penalty.cpu() + score = emissions[:, 0].float() + start_penalty + history = [] + finals = {} + for position in range(1, max(lengths)): + for index, length in enumerate(lengths): + if length == position: + finals[index] = (score[index] + end_penalty).argmax().item() + score, previous = (score.unsqueeze(2) + transitions).max(1) + score = score + emissions[:, position].float() + history.append(previous.cpu()) + states = (score + end_penalty).argmax(1).tolist() + paths = [] + for index, length in enumerate(lengths): + current = finals.get(index, states[index]) + path = [current] + for position in range(length - 2, -1, -1): + current = history[position][index, current].item() + path.append(current) + paths.append(list(reversed(path))) + return paths + + +def decode_bio(logits: Tensor, lengths: list[int], names: tuple[str, ...]) -> list[list[int]]: + start = torch.zeros(logits.shape[-1], device=logits.device) + start[2::2] = -10000 + return viterbi_paths(logits, lengths, legal_transitions(names, logits.device), start, torch.zeros_like(start)) + + +def joint_states() -> list[tuple[int, int, int]]: + person_begin = 1 + 2 * OUTER_NAMES.index('person') + person_inside = person_begin + 1 + states = [(outer, 0, 0) for outer in range(1 + 2 * len(OUTER_NAMES)) if outer not in (person_begin, person_inside)] + states += [(person_begin, 0, 0), (person_begin, 1, 1), (person_begin, 3, 2)] + for seen in range(4): + states.append((person_inside, 0, seen)) + for name in range(1, 5): + bit = 1 if name <= 2 else 2 + if seen & bit: + states.append((person_inside, name, seen)) + return states + + +@lru_cache(maxsize=1) +def joint_constraint_tables() -> tuple[list[tuple[int, int, int]], Tensor, Tensor, Tensor]: + states = joint_states() + person_begin = 1 + 2 * OUTER_NAMES.index('person') + person_inside = person_begin + 1 + transitions = torch.full((len(states), len(states)), -10000., device='cpu') + for previous, (a, n, seen) in enumerate(states): + for current, (b, m, after) in enumerate(states): + if b and b % 2 == 0 and a not in (b - 1, b): + continue + if m and m % 2 == 0 and n not in (m - 1, m): + continue + if a in (person_begin, person_inside) and b != person_inside and not seen: + continue + if b == person_inside: + bit = 0 if not m else 1 if m <= 2 else 2 + if m % 2 == 1 and seen & bit: + continue + if after != seen | bit: + continue + transitions[previous, current] = 0 + start = torch.tensor([-10000. if a and a % 2 == 0 else 0. for a, _, _ in states], device='cpu') + end = torch.tensor([-10000. if a in (person_begin, person_inside) and not seen else 0. + for a, _, seen in states], device='cpu') + return states, transitions, start, end + + +def decode_joint(outer_logits: Tensor, name_logits: Tensor, lengths: list[int], + name_weight: float = 1.) -> list[list[list[int]]]: + """人物内の姓名、各部分の一意性、人物の必須姓名をBIOと同時に満たす。""" + states, transitions, start, end = joint_constraint_tables() + device = outer_logits.device + transitions, start, end = transitions.to(device), start.to(device), end.to(device) + outer_ids = torch.tensor([a for a, _, _ in states], device=device) + name_ids = torch.tensor([n for _, n, _ in states], device=device) + emissions = outer_logits.float()[..., outer_ids] + name_weight * name_logits.float()[..., name_ids] + paths = viterbi_paths(emissions, lengths, transitions, start, end) + return [[[states[state][column] for state in path] for path in paths] for column in (0, 1)] + + +def bio_spans(labels: list[int], names: tuple[str, ...]) -> list[tuple[str, int, int]]: + spans = [] + start = 0 + active = None + for position, label in enumerate([*labels, 0]): + name = names[(label - 1) // 2] if label else None + if active is not None and (name != active or label % 2 == 1): + spans.append((active, start, position)) + active = None + if name is not None and active is None: + active, start = name, position + return spans + + +def prediction_from_labels(identifier: str, text: str, outer: list[int], names: list[int]) -> dict: + result = {'id': identifier, 'fields': [], 'contributors': []} + name_spans = bio_spans(names, NAME_NAMES) + for label, start, end in bio_spans(outer, OUTER_NAMES): + span = {'start': start, 'end': end, 'value': visible_value(text[start:end], label)} + if label in FIELD_NAMES: + result['fields'].append({'label': label, **span}) + else: + parts = {} + if label == 'person': + for part, a, b in name_spans: + if start <= a < b <= end and part not in parts: + parts[part] = {'start': a, 'end': b, 'value': visible_value(text[a:b], part)} + if not parts: + # 不正な人物を補完せず欠落予測にし、採点の分母に残す。 + continue + result['contributors'].append({'kind': label, **span, 'name_parts': parts}) + validate_target(text, result) + return result + + +def decode_predictions(logits: list[Tensor], rows: list[EncodedCitation], decoder: str, + name_weight: float = 1., lexicon: dict | None = None) -> list[dict]: + lengths = [len(row.text) for row in rows] + if decoder == 'joint': + paths = decode_joint(logits[0], logits[1], lengths, name_weight) + else: + paths = [decode_bio(scores, lengths, names) for scores, names in zip(logits[:2], LAYERS)] + predictions = [] + for row, outer, names in zip(rows, *paths): + prediction = prediction_from_labels(row.identifier, row.text, outer, names) + if lexicon is not None: + from shared.training_lexicon import apply_training_lexicon + prediction = apply_training_lexicon(row.text, prediction, lexicon) + predictions.append(prediction) + return predictions + + +def preserve_baseline_structure(baseline: dict, candidate: dict) -> dict: + """書誌項目と人物範囲を保ち、同じ人物範囲の姓名だけを候補から採る。""" + result = deepcopy(baseline) + replacements = {(p['kind'], p['start'], p['end']): p['name_parts'] + for p in candidate['contributors'] if p['kind'] == 'person'} + for person in result['contributors']: + key = person['kind'], person['start'], person['end'] + if key in replacements: + person['name_parts'] = deepcopy(replacements[key]) + return result + + +@torch.inference_mode() +def predict(model: CharacterTagger | EnsembleTagger, rows: list[EncodedCitation], tokenizer: PreTrainedTokenizerFast, + batch_size: int, device: str, precision: str = 'fp32') -> list[dict]: + if precision not in {'fp32', 'bf16'}: + raise ValueError('unknown_inference_precision') + model.eval() + predictions = {} + ordered = sorted(rows, key=lambda row: len(row.input_ids)) + for begin in range(0, len(ordered), batch_size): + chunk = ordered[begin:begin + batch_size] + tensors = collate(chunk, tokenizer.pad_token_id, device) + with torch.autocast(device_type=device, dtype=torch.bfloat16, enabled=device == 'cuda' and precision == 'bf16'): + if isinstance(model, EnsembleTagger) and (model.member_tokenizers is not None or model.ensemble_script_weights is not None + or getattr(model, 'candidate_reranker', None) is not None + or getattr(model, 'score_calibrator', None) is not None + or getattr(model, 'inference_strategy', None) is not None): + outputs = (model.member_text_outputs(chunk, device) if model.member_tokenizers is not None + else model.member_outputs(**tensors)) + logits = combine_ensemble_logits(outputs, model.weights_for_rows(chunk)) + else: + logits = model(**tensors) + if getattr(model, 'inference_strategy', None) is not None: + from shared.inference_strategies import predict_from_outputs + decoded = predict_from_outputs(outputs, model.weights_for_rows(chunk), chunk, + getattr(model, 'score_calibrator', None), model.inference_strategy, model.name_weight) + for prediction in decoded: + predictions[prediction['id']] = prediction + continue + uncalibrated_logits = logits + if getattr(model, 'score_calibrator', None) is not None: + logits = model.score_calibrator.calibrate(outputs, [row.text for row in chunk], logits) + if getattr(model, 'candidate_reranker', None) is not None: + from shared.candidate_reranker import rerank_predictions + decoded = rerank_predictions(model, outputs, chunk, model.reranker_configuration) + else: + decoded = decode_predictions(logits, chunk, model.decoder, model.name_weight, model.training_lexicon) + name_scope = (getattr(model, 'score_calibrator', None) is not None + and model.score_calibrator.configuration.get('decode_scope') == 'names') + if name_scope: + original = decode_predictions(uncalibrated_logits, chunk, model.decoder, model.name_weight, model.training_lexicon) + decoded = [preserve_baseline_structure(before, after) for before, after in zip(original, decoded, strict=True)] + if getattr(model, 'name_boundary_prior', None) is not None: + from shared.name_boundary_prior import apply_name_boundary_prior, merge_name_corrections + name_scores = (uncalibrated_logits if name_scope else logits)[1].float().cpu().numpy() + dictionary_predictions = [apply_name_boundary_prior(row.text, prediction, name_scores[i, :len(row.text)], + model.name_boundary_prior, model.name_boundary_settings, model.name_boundary_protected) + for i, (row, prediction) in enumerate(zip(chunk, original if name_scope else decoded, strict=True))] + decoded = ([merge_name_corrections(before, learned, dictionary) for before, learned, dictionary in + zip(original, decoded, dictionary_predictions, strict=True)] if name_scope else dictionary_predictions) + if getattr(model, 'date_qualifiers', None): + from shared.date_qualifier import extend_date_qualifiers + decoded = [extend_date_qualifiers(row.text, prediction, model.date_qualifiers) + for row, prediction in zip(chunk, decoded, strict=True)] + if getattr(model, 'doi_volume_prior', None): + from shared.doi_volume_prior import apply_doi_volume_prior + decoded = [apply_doi_volume_prior(prediction, model.doi_volume_prior) for prediction in decoded] + if getattr(model, 'name_conventions', None): + from shared.name_conventions import apply_name_conventions + decoded = [apply_name_conventions(row.text, prediction, model.name_conventions) + for row, prediction in zip(chunk, decoded, strict=True)] + if getattr(model, 'field_fragment_rules', None): + from shared.field_fragments import merge_field_fragments + decoded = [merge_field_fragments(row.text, prediction, model.field_fragment_rules) + for row, prediction in zip(chunk, decoded, strict=True)] + for prediction in decoded: + predictions[prediction['id']] = prediction + return [predictions[row.identifier] for row in rows] + + +def model_weights_path(folder: Path, config: dict | None = None) -> Path: + configuration = config if config is not None else json.loads((folder / 'tagger.json').read_text()) + compression = configuration.get('weights_compression', 'none') + if compression not in ('none', 'gzip', 'zstd'): + raise ValueError('unsupported_weight_compression') + return folder / {'none': 'model.safetensors', 'gzip': 'model.safetensors.gz', + 'zstd': 'model.safetensors.zst'}[compression] + + +def load_character_model(folder: Path, config: dict) -> CharacterTagger: + from safetensors.torch import load_file, load + model = CharacterTagger(config) + path = model_weights_path(folder, config) + if config.get('weights_compression') == 'gzip': + weights = load(gzip.decompress(path.read_bytes())) + elif config.get('weights_compression') == 'zstd': + weights = load(zstd.decompress(path.read_bytes())) + else: + weights = load_file(path) + if config.get('weights_format') == 'rowwise_int8': + from shared.weight_storage import decode_int8_weights + weights = decode_int8_weights(weights) + elif config.get('weights_format') == 'groupwise_int6': + from shared.weight_storage import decode_int6_weights + weights = decode_int6_weights(weights) + elif config.get('weights_format') == 'groupwise_int4': + from shared.weight_storage import decode_int4_weights + weights = decode_int4_weights(weights) + if config.get('outer_adapter') and not any(key.startswith('outer_adapter.') for key in weights): + missing = model.load_state_dict(weights, strict=False) + if set(missing.missing_keys) != {'outer_adapter.weight', 'outer_adapter.bias'} or missing.unexpected_keys: + raise ValueError('outer_adapter_base_weights_mismatch') + model.outer_adapter.load_state_dict(load_file(folder / config['outer_adapter']['file'])) + else: + model.load_state_dict(weights) + return model + + +def load_package(folder: Path, device: str) -> tuple[CharacterTagger | EnsembleTagger, PreTrainedTokenizerFast, dict]: + config = json.loads((folder / 'tagger.json').read_text()) + if config.get('ensemble_members'): + configurations = [json.loads((folder / name / 'tagger.json').read_text()) for name in config['ensemble_members']] + expected_manifests = config.get('ensemble_member_training_manifests', + [config['dataset_manifest_sha256']]*len(configurations)) + if len(expected_manifests) != len(configurations) or any( + value['dataset_manifest_sha256'] != expected for value, expected in zip(configurations, expected_manifests)): + raise ValueError('ensemble_dataset_mismatch') + expected_schema = config.get('schema_version', configurations[0].get('schema_version')) + if any(value.get('schema_version') != expected_schema for value in configurations): + raise ValueError('ensemble_schema_mismatch') + members = [load_character_model(folder / name, value) for name, value in zip(config['ensemble_members'], configurations)] + model = EnsembleTagger(members, configurations, config) + else: + model = load_character_model(folder, config) + if isinstance(model, EnsembleTagger) and config.get('ensemble_tokenizers') is not None: + if len(config['ensemble_tokenizers']) != len(model.members): + raise ValueError('ensemble_tokenizer_count_mismatch') + model.member_tokenizers = [AutoTokenizer.from_pretrained(folder / location, local_files_only=True) + for location in config['ensemble_tokenizers']] + tokenizer = model.member_tokenizers[0] + else: + tokenizer = AutoTokenizer.from_pretrained(folder, local_files_only=True) + if config.get('use_training_lexicon'): + from shared.training_lexicon import load_training_lexicon + model.training_lexicon = load_training_lexicon(folder, config) + if model.training_lexicon['dataset_manifest_sha256'] != config['dataset_manifest_sha256']: + raise ValueError('training_lexicon_dataset_mismatch') + if config.get('candidate_reranker'): + if not isinstance(model, EnsembleTagger) or len(model.members) != 4: + raise ValueError('candidate_reranker_requires_four_members') + from shared.candidate_reranker import CandidateReranker + model.candidate_reranker = CandidateReranker(folder, config['candidate_reranker']) + model.reranker_configuration = config + if config.get('score_calibration'): + if not isinstance(model, EnsembleTagger) or len(model.members) != 4 or config.get('candidate_reranker'): + raise ValueError('score_calibration_requires_four_members_without_reranker') + from shared.score_calibration import ScoreCalibrator, LabelScoreCalibrator, DynamicMixtureCalibrator + from safetensors.torch import load_file + calibrator = {'label_mix': LabelScoreCalibrator, 'dynamic_mix': DynamicMixtureCalibrator}.get(config['score_calibration'].get('kind'), ScoreCalibrator) + model.score_calibrator = calibrator(config['score_calibration']) + model.score_calibrator.load_state_dict(load_file(folder / 'score_calibration.safetensors')) + if config.get('name_boundary_prior'): + scoped_calibration = (config.get('score_calibration', {}).get('decode_scope') == 'names' + and config['name_boundary_prior'].get('merge_mode') == 'independent_edits') + if (not isinstance(model, EnsembleTagger) or config.get('candidate_reranker') + or (config.get('score_calibration') and not scoped_calibration)): + raise ValueError('name_prior_requires_unmodified_ensemble_scores') + from compression import zstd + from shared.training_lexicon import name_lookup + settings = config['name_boundary_prior'] + model.name_boundary_prior = json.loads(zstd.decompress((folder / 'name_boundary_prior.json.zst').read_bytes())) + if model.name_boundary_prior['schema'] != 'bibliography-name-boundary-prior/1': + raise ValueError('unsupported_name_boundary_prior_schema') + model.name_boundary_settings = settings + model.name_boundary_protected = set(name_lookup(model.training_lexicon)) if model.training_lexicon else set() + model.date_qualifiers = config.get('date_qualifiers', []) + model.name_conventions = config.get('name_conventions', []) + model.field_fragment_rules = config.get('field_fragment_rules', []) + if config.get('doi_volume_prior'): + model.doi_volume_prior = json.loads((folder / config['doi_volume_prior']).read_text())['rules'] + if 'inference_strategy' in config: + if not isinstance(model, EnsembleTagger) or config.get('use_training_lexicon') or config.get('name_boundary_prior') or config.get('doi_volume_prior'): + raise ValueError('text_only_strategy_requires_ensemble_without_lookup_tables') + model.inference_strategy = config['inference_strategy'] + return model.to(device).eval(), tokenizer, config diff --git a/pytorch/shared/text_offsets.py b/pytorch/shared/text_offsets.py new file mode 100644 index 0000000000000000000000000000000000000000..e389625bea8cd984e105a8cba74cb8503cd10db4 --- /dev/null +++ b/pytorch/shared/text_offsets.py @@ -0,0 +1,8 @@ +"""文字の置換と同時に、Unicodeコードポイントで表した範囲を移し替える。""" + + +def transform_characters(text: str,annotations: list[tuple[str,int,int]],replacements: list[str]) -> tuple[str,list[tuple[str,int,int]]]: + if len(replacements)!=len(text):raise ValueError("replacement_length_mismatch") + offsets=[0] + for value in replacements:offsets.append(offsets[-1]+len(value)) + return "".join(replacements),[(label,offsets[start],offsets[end]) for label,start,end in annotations if offsets[start] dict: + compression = configuration.get('training_lexicon_compression', 'none') + if compression == 'none': + raw = (folder / 'training_lexicon.json').read_bytes() + elif compression == 'zstd': + raw = zstd.decompress((folder / 'training_lexicon.json.zst').read_bytes()) + else: + raise ValueError('unsupported_training_lexicon_compression') + return json.loads(raw) + + +@lru_cache(maxsize=100000) +def normalize_with_offsets(text: str, fold_case: bool = False) -> tuple[str, tuple[tuple[int, int], ...]]: + units = [] + for match in re.finditer(r'\s+|\S', text): + char = ' ' if match[0].isspace() else match[0].translate(str.maketrans({',': ',', ':': ':', '–': '-', '—': '-'})) + if fold_case: + folded = char.casefold() + char = folded if len(folded) == 1 else char + units.append((char, match.start(), match.end())) + if units and units[0][0] == ' ': + units.pop(0) + if units and units[-1][0] == ' ': + units.pop() + return ''.join(row[0] for row in units), tuple((row[1], row[2]) for row in units) + + +def add_name_evidence(table: dict, text: str, parts: dict[str, tuple[int, int]]) -> None: + key, positions = normalize_with_offsets(text) + signature = [] + for part in ('family', 'given'): + if part not in parts: + signature.extend((-1, -1)) + continue + start, end = parts[part] + selected = [i for i, (a, b) in enumerate(positions) if a >= start and b <= end] + if not selected: + return + signature.extend((min(selected), max(selected) + 1)) + if key and signature != [-1, -1, -1, -1]: + table[key].add(tuple(signature)) + + +def add_raw_name_evidence(table: dict, family: str, given: str) -> None: + for display_family in {family, family.upper()}: + if not display_family: + continue + add_name_evidence(table, display_family, {'family': (0, len(display_family))}) + if not given: + continue + for separator in (' ', ', ', ''): + value = display_family + separator + given + add_name_evidence(table, value, {'family': (0, len(display_family)), + 'given': (len(display_family) + len(separator), len(value))}) + for separator in (' ', ''): + value = given + separator + display_family + add_name_evidence(table, value, {'given': (0, len(given)), + 'family': (len(given) + len(separator), len(value))}) + + +def name_lookup(lexicon: dict) -> dict: + if lexicon['schema_version'] == SCHEMA: + return lexicon['names'] + if '_name_lookup' not in lexicon: + names = defaultdict(set) + for key, signature in lexicon['names'].items(): + names[key].add(tuple(signature)) + for family, given in lexicon['raw_names']: + add_raw_name_evidence(names, family, given) + ambiguous = set(lexicon['ambiguous_names']) + lexicon['_name_lookup'] = {key: next(iter(values)) for key, values in names.items() + if len(values) == 1 and key not in ambiguous} + return lexicon['_name_lookup'] + + +def has_unclosed_parenthesis(value: str) -> bool: + value = value.translate(str.maketrans('()', '()')) + return value.count('(') > value.count(')') + + +def build_training_lexicon(dataset: Path, compact_names: bool = False, + close_title_parentheses: bool = False, + numeric_field_min_sources: int = 0) -> dict: + """trainの表示名と、trainの原書誌に明示された姓名だけを収録する。""" + def rows(name: str) -> list[dict]: + with (dataset / name).open() as stream: + return [json.loads(line) for line in stream] + if numeric_field_min_sources < 0: + raise ValueError('invalid_numeric_field_min_sources') + inputs = {row['id']: row['text'] for row in rows('train/inputs.jsonl')} + names = defaultdict(set) + fields = defaultdict(set) + targets = rows('train/targets.jsonl') + if set(inputs) != {row['id'] for row in targets}: + raise ValueError('lexicon_training_id_mismatch') + for row in targets: + text = inputs[row['id']] + validate_target(text, row) + for person in row['contributors']: + if person['kind'] == 'person': + parts = {part: (span['start'] - person['start'], span['end'] - person['start']) + for part, span in person['name_parts'].items()} + add_name_evidence(names, text[person['start']:person['end']], parts) + for field in row['fields']: + fields[normalize_with_offsets(field['value'], True)[0]].add(field['label']) + train_ids = {row['source_id'] for row in rows('source_splits.jsonl') if row['split'] == 'train'} + observed = set() + raw_names = set() + for record in rows('corpus/accepted.jsonl'): + if record['source_id'] not in train_ids: + continue + observed.add(record['source_id']) + for value, label in ((record['title'], 'TITLE'), (record['publisher'], 'ISSUER'), + (record['fields'].get('container', ''), 'CONTAINER_TITLE')): + if value: + fields[normalize_with_offsets(value, True)[0]].add(label) + for person in record['people']: + if person.get('literal'): + continue + family, given = person.get('family', ''), person.get('given', '') + if compact_names: + raw_names.add((family, given)) + else: + add_raw_name_evidence(names, family, given) + if observed != train_ids: + raise ValueError('lexicon_training_sources_missing') + unambiguous_names = {key: next(iter(values)) for key, values in names.items() if len(values) == 1} + unambiguous_fields = {key: next(iter(values)) for key, values in fields.items() + if len(values) == 1 and len(key) >= 5 + and next(iter(values)) in ('CONTAINER_TITLE', 'ISSUER')} + result = {'schema_version': COMPACT_SCHEMA if compact_names else SCHEMA, + 'dataset_manifest_sha256': hashlib.sha256((dataset / 'manifest.json').read_bytes()).hexdigest(), + 'training_sources': len(train_ids), 'names': unambiguous_names, 'fields': unambiguous_fields, + 'source_files': {name: hashlib.sha256((dataset / name).read_bytes()).hexdigest() + for name in ('train/inputs.jsonl', 'train/targets.jsonl', 'source_splits.jsonl', 'corpus/accepted.jsonl')}} + if compact_names: + result['raw_names'] = sorted(raw_names) + result['ambiguous_names'] = sorted(key for key, values in names.items() if len(values) > 1) + raw_evidence = defaultdict(set) + for family, given in raw_names: + add_raw_name_evidence(raw_evidence, family, given) + # 原書誌から同じ範囲を再現できる表記は、明示表へ重複保存しない。 + result['names'] = {key: signature for key, signature in unambiguous_names.items() + if len(raw_evidence.get(key, set())) != 1 + or signature != next(iter(raw_evidence[key]))} + if close_title_parentheses: + positive = negative = 0 + for row in targets: + text = inputs[row['id']] + for field in row['fields']: + if field['label'] != 'TITLE': + continue + value = text[field['start']:field['end']] + if field['end'] < len(text) and text[field['end']] in '))' and has_unclosed_parenthesis(value): + negative += 1 + if value.endswith((')', ')')) and has_unclosed_parenthesis(value[:-1]) and not has_unclosed_parenthesis(value): + positive += 1 + if positive < 10 or negative: + raise ValueError('training_titles_do_not_support_parenthesis_completion') + result['title_parenthesis_completion'] = {'enabled': True, 'training_positive': positive, 'training_negative': negative} + if numeric_field_min_sources: + metadata = {row['id']: row for row in rows('train/metadata.jsonl')} + if set(metadata) != set(inputs) or any(row['source_id'] not in train_ids for row in metadata.values()): + raise ValueError('numeric_field_training_sources_mismatch') + evidence = defaultdict(lambda: defaultdict(set)) + for row in targets: + containers = {normalize_with_offsets(field['value'], True)[0] for field in row['fields'] + if field['label'] == 'CONTAINER_TITLE'} + if len(containers) != 1: + continue + container = next(iter(containers)) + for field in row['fields']: + if field['label'] in ('DATE', 'VOLUME', 'ISSUE', 'PAGES') and re.fullmatch(r'\d{1,4}', field['value']): + evidence[(container, field['value'])][field['label']].add(metadata[row['id']]['source_id']) + labels = defaultdict(dict) + for (container, value), alternatives in sorted(evidence.items()): + if len(alternatives) == 1: + label, sources = next(iter(alternatives.items())) + if len(sources) >= numeric_field_min_sources: + labels[container][value] = label + result['container_numeric_labels'] = {'minimum_sources': numeric_field_min_sources, 'labels': dict(labels)} + result['source_files']['train/metadata.jsonl'] = hashlib.sha256((dataset / 'train/metadata.jsonl').read_bytes()).hexdigest() + return result + + +def apply_training_lexicon(text: str, prediction: dict, lexicon: dict) -> dict: + if lexicon['schema_version'] not in (SCHEMA, COMPACT_SCHEMA): + raise ValueError('unsupported_training_lexicon_schema') + result = deepcopy(prediction) + names = name_lookup(lexicon) + for person in result['contributors']: + if person['kind'] != 'person': + continue + key, positions = normalize_with_offsets(text[person['start']:person['end']]) + signature = names.get(key) + if signature is None: + continue + parts = {} + for index, part in enumerate(('family', 'given')): + a, b = signature[index * 2:index * 2 + 2] + if a >= 0: + start = person['start'] + positions[a][0] + end = person['start'] + positions[b - 1][1] + parts[part] = {'start': start, 'end': end, 'value': visible_value(text[start:end], part)} + person['name_parts'] = parts + additional_fields = [] + for field in result['fields']: + if field['label'] not in ('CONTAINER_TITLE', 'ISSUER'): + continue + key, positions = normalize_with_offsets(text[field['start']:field['end']], True) + start, end = 0, len(key) + label = lexicon['fields'].get(key) + if label is None: + while start < end and (key[start].isspace() or key[start] in '.,;:()()[]"“”‘’'): + start += 1 + while start < end and (key[end - 1].isspace() or key[end - 1] in '.,;:()()[]"“”‘’'): + end -= 1 + label = lexicon['fields'].get(key[start:end]) + if label: + a = field['start'] + positions[start][0] + b = field['start'] + positions[end - 1][1] + field.update(label=label, start=a, end=b, value=visible_value(text[a:b], label)) + else: + # 完全な刊行物名を優先し、両側が既知の場合だけ混入した発行者を分ける。 + value = text[field['start']:field['end']] + match = re.fullmatch(r'(.+?)\s*[\((\[]\s*(.+?)\s*[\))\]]\s*', value) + if match and lexicon['fields'].get(normalize_with_offsets(match[1], True)[0]) == 'CONTAINER_TITLE' and lexicon['fields'].get(normalize_with_offsets(match[2], True)[0]) == 'ISSUER': + offset = field['start'] + separated = [] + for index, kind in ((1, 'CONTAINER_TITLE'), (2, 'ISSUER')): + a, b = match.span(index) + while a < b and value[a].isspace(): + a += 1 + while b > a and value[b - 1].isspace(): + b -= 1 + separated.append({'label': kind, 'start': offset + a, 'end': offset + b, + 'value': visible_value(value[a:b], kind)}) + field.update(separated[0]) + additional_fields.append(separated[1]) + result['fields'].extend(additional_fields) + result['fields'].sort(key=lambda field: (field['start'], field['end'])) + if lexicon.get('title_parenthesis_completion', {}).get('enabled'): + for field in result['fields']: + end = field['end'] + if (field['label'] == 'TITLE' and end < len(text) and text[end] in '))' + and has_unclosed_parenthesis(text[field['start']:end]) + and not any(other is not field and other['start'] <= end < other['end'] + for other in result['fields'] + result['contributors'])): + field.update(end=end + 1, value=visible_value(text[field['start']:end + 1], 'TITLE')) + numeric_labels = lexicon.get('container_numeric_labels', {}).get('labels', {}) + containers = {normalize_with_offsets(field['value'], True)[0] for field in result['fields'] + if field['label'] == 'CONTAINER_TITLE'} + if len(containers) == 1: + labels = numeric_labels.get(next(iter(containers)), {}) + for field in result['fields']: + if field['label'] not in ('DATE', 'VOLUME', 'ISSUE', 'PAGES'): + continue + label = labels.get(field['value']) + if label and label != field['label'] and not any(other['label'] == label for other in result['fields']): + field['label'] = label + validate_target(text, result) + return result diff --git a/pytorch/shared/weight_storage.py b/pytorch/shared/weight_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1595d9fddf95e70e6605edf24df7cf4909cf01 --- /dev/null +++ b/pytorch/shared/weight_storage.py @@ -0,0 +1,218 @@ +"""4・6・8bitで重みを保存し、推論時に浮動小数点へ復元する。""" + +import re + +import torch +from torch import Tensor + +SCALE_PREFIX = '__row_scale__.' + + +def encode_int8_weights(state: dict[str, Tensor]) -> dict[str, Tensor]: + stored = {} + for key, value in state.items(): + if key.startswith(SCALE_PREFIX): + raise ValueError('reserved_weight_key') + value = value.detach().cpu().contiguous() + if value.is_floating_point() and value.ndim >= 2 and value.numel() >= 4096: + rows = value.float().reshape(value.shape[0], -1) + scales = (rows.abs().amax(1) / 127).clamp_min(1e-12) + if not torch.isfinite(scales).all(): + raise ValueError('non_finite_model_weight') + stored[key] = (rows / scales[:, None]).round().clamp(-127, 127).to(torch.int8).reshape(value.shape) + stored[SCALE_PREFIX + key] = scales + else: + stored[key] = value.half() if value.is_floating_point() else value + return stored + + +def decode_int8_weights(stored: dict[str, Tensor]) -> dict[str, Tensor]: + state = {} + for key, value in stored.items(): + if key.startswith(SCALE_PREFIX): + continue + scales = stored.get(SCALE_PREFIX + key) + if scales is None: + state[key] = value + else: + if value.dtype != torch.int8 or scales.shape != (value.shape[0],): + raise ValueError('invalid_quantized_weight') + state[key] = (value.float().reshape(value.shape[0], -1) * scales[:, None]).reshape(value.shape) + return state + + +def fake_quantize_int8(value: Tensor) -> Tensor: + """行ごとの8bit保存と同じ丸めを使い、勾配を元の重みへ通す。""" + with torch.no_grad(): + rows = value.detach().float().reshape(value.shape[0], -1) + scales = (rows.abs().amax(1) / 127).clamp_min(1e-12) + restored = ((rows / scales[:, None]).round().clamp(-127, 127) * scales[:, None]).reshape(value.shape) + return value + (restored.to(value.dtype) - value).detach() + + +class Int8TrainingWeight(torch.nn.Module): + def forward(self, weight: Tensor) -> Tensor: + return fake_quantize_int8(weight) + + +def enable_int8_training(model: torch.nn.Module) -> None: + from torch.nn.utils import parametrize + # 8bit保存ではLSTMの行列も量子化するため、名前付きの全行列を対象にする。 + targets = [(module, name) for module in model.modules() + for name, value in module.named_parameters(recurse=False) + if value.is_floating_point() and value.ndim >= 2 and value.numel() >= 4096] + for module, name in targets: + parametrize.register_parametrization(module, name, Int8TrainingWeight()) + + +INT4_GROUP_SIZE = 128 +GROUP_SCALE_PREFIX = '__group_scale__.' +SHAPE_PREFIX = '__weight_shape__.' + + +def fake_quantize_int4(value: Tensor) -> Tensor: + """保存・復元と同じ丸めを使い、勾配は元の重みへ通す。""" + with torch.no_grad(): + flat = value.detach().float().flatten() + padding = (-flat.numel()) % INT4_GROUP_SIZE + groups = torch.nn.functional.pad(flat, (0, padding)).reshape(-1, INT4_GROUP_SIZE) + scales = (groups.abs().amax(1) / 7).clamp_min(1e-6).half().float() + dequantized = ((groups / scales[:, None]).round().clamp(-7, 7) * scales[:, None]).flatten()[:flat.numel()] + return value + (dequantized.reshape(value.shape).to(value.dtype) - value).detach() + + +def encode_int4_weights(state: dict[str, Tensor]) -> dict[str, Tensor]: + stored = {} + for key, value in state.items(): + if key.startswith((GROUP_SCALE_PREFIX, SHAPE_PREFIX)): + raise ValueError('reserved_weight_key') + value = value.detach().cpu().contiguous() + if value.is_floating_point() and value.ndim >= 2 and value.numel() >= 4096 and not key.startswith('recurrent.'): + flat = value.float().flatten() + groups = torch.nn.functional.pad(flat, (0, (-flat.numel()) % INT4_GROUP_SIZE)).reshape(-1, INT4_GROUP_SIZE) + scales = (groups.abs().amax(1) / 7).clamp_min(1e-6).half() + if not torch.isfinite(scales).all(): + raise ValueError('non_finite_model_weight') + codes = ((groups / scales.float()[:, None]).round().clamp(-7, 7).to(torch.int16) + 8).flatten() + stored[key] = (codes[0::2] | (codes[1::2] << 4)).to(torch.uint8) + stored[GROUP_SCALE_PREFIX + key] = scales + stored[SHAPE_PREFIX + key] = torch.tensor(value.shape, dtype=torch.int64) + else: + stored[key] = value.half() if value.is_floating_point() else value + return stored + + +def decode_int4_weights(stored: dict[str, Tensor]) -> dict[str, Tensor]: + state = {} + for key, value in stored.items(): + if key.startswith((GROUP_SCALE_PREFIX, SHAPE_PREFIX)): + continue + scales = stored.get(GROUP_SCALE_PREFIX + key) + if scales is None: + state[key] = value + else: + shape = tuple(stored[SHAPE_PREFIX + key].tolist()) + codes = torch.stack((value & 15, value >> 4), -1).flatten().to(torch.int16) - 8 + restored = codes.reshape(-1, INT4_GROUP_SIZE).float() * scales.float()[:, None] + size = 1 + for length in shape: + size *= length + state[key] = restored.flatten()[:size].reshape(shape) + return state + + +class Int4TrainingWeight(torch.nn.Module): + def forward(self, weight: Tensor) -> Tensor: + return fake_quantize_int4(weight) + + +def enable_int4_training(model: torch.nn.Module) -> None: + from torch.nn.utils import parametrize + # 差し替えにより子moduleが増えるため、先に対象を確定する。 + modules = [module for module in model.modules() + if isinstance(module, (torch.nn.Linear, torch.nn.Embedding, torch.nn.Conv1d)) + and module.weight.ndim >= 2 and module.weight.numel() >= 4096] + for module in modules: + parametrize.register_parametrization(module, 'weight', Int4TrainingWeight()) + + +def plain_state_dict(model: torch.nn.Module) -> dict[str, Tensor]: + return {re.sub(r'(^|\.)parametrizations\.([^.]+)\.original$', r'\1\2', key): value + for key, value in model.state_dict().items()} + + +# 最大コードを7から28にし、4bitで保存した重みの格子を細分化する。 +INT6_MAXIMUM = 28 + + +def fake_quantize_int6(value: Tensor) -> Tensor: + with torch.no_grad(): + flat = value.detach().float().flatten() + groups = torch.nn.functional.pad(flat, (0, (-flat.numel()) % INT4_GROUP_SIZE)).reshape(-1, INT4_GROUP_SIZE) + scales = (groups.abs().amax(1) / INT6_MAXIMUM).clamp_min(1e-6).half().float() + restored = ((groups / scales[:, None]).round().clamp(-INT6_MAXIMUM, INT6_MAXIMUM) * scales[:, None]).flatten()[:flat.numel()] + return value + (restored.reshape(value.shape).to(value.dtype) - value).detach() + + +def encode_int6_weights(state: dict[str, Tensor]) -> dict[str, Tensor]: + stored = {} + for key, value in state.items(): + if key.startswith((GROUP_SCALE_PREFIX, SHAPE_PREFIX)): + raise ValueError('reserved_weight_key') + value = value.detach().cpu().contiguous() + if value.is_floating_point() and value.ndim >= 2 and value.numel() >= 4096 and not key.startswith('recurrent.'): + flat = value.float().flatten() + groups = torch.nn.functional.pad(flat, (0, (-flat.numel()) % INT4_GROUP_SIZE)).reshape(-1, INT4_GROUP_SIZE) + scales = (groups.abs().amax(1) / INT6_MAXIMUM).clamp_min(1e-6).half() + if not torch.isfinite(scales).all(): + raise ValueError('non_finite_model_weight') + codes = ((groups / scales.float()[:, None]).round().clamp(-INT6_MAXIMUM, INT6_MAXIMUM).to(torch.int16) + 32).flatten() + a, b, c, d = (codes[index::4] for index in range(4)) + # 同じビット位置のバイトを並べると、値を変えずに圧縮率が上がる。 + stored[key] = torch.stack((a | ((b & 3) << 6), (b >> 2) | ((c & 15) << 4), + (c >> 4) | (d << 2)), 0).to(torch.uint8) + stored[GROUP_SCALE_PREFIX + key] = scales + stored[SHAPE_PREFIX + key] = torch.tensor(value.shape, dtype=torch.int64) + else: + stored[key] = value.half() if value.is_floating_point() else value + return stored + + +def decode_int6_weights(stored: dict[str, Tensor]) -> dict[str, Tensor]: + state = {} + for key, value in stored.items(): + if key.startswith((GROUP_SCALE_PREFIX, SHAPE_PREFIX)): + continue + scales = stored.get(GROUP_SCALE_PREFIX + key) + if scales is None: + state[key] = value + else: + shape = tuple(stored[SHAPE_PREFIX + key].tolist()) + if value.ndim == 2 and value.shape[0] == 3: + a, b, c = value.unbind(0) + elif value.ndim == 1: + a, b, c = value[0::3], value[1::3], value[2::3] + else: + raise ValueError('invalid_int6_byte_layout') + codes = torch.stack((a & 63, (a >> 6) | ((b & 15) << 2), + (b >> 4) | ((c & 3) << 4), c >> 2), -1).flatten().to(torch.int16) - 32 + groups = codes.reshape(-1, INT4_GROUP_SIZE).float() * scales.float()[:, None] + size = 1 + for length in shape: + size *= length + state[key] = groups.flatten()[:size].reshape(shape) + return state + + +class Int6TrainingWeight(torch.nn.Module): + def forward(self, weight: Tensor) -> Tensor: + return fake_quantize_int6(weight) + + +def enable_int6_training(model: torch.nn.Module) -> None: + from torch.nn.utils import parametrize + modules = [module for module in model.modules() + if isinstance(module, (torch.nn.Linear, torch.nn.Embedding, torch.nn.Conv1d)) + and module.weight.ndim >= 2 and module.weight.numel() >= 4096] + for module in modules: + parametrize.register_parametrization(module, 'weight', Int6TrainingWeight()) diff --git a/web-src/README.md b/web-src/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4f2f34d00c23ff70812a6799126f98dc99516611 --- /dev/null +++ b/web-src/README.md @@ -0,0 +1,11 @@ +# ブラウザ版をビルドする + +Node.jsとnpmを用意し、このディレクトリで実行します。 + +```bash +npm ci +npm run typecheck +npm run build -- ../onnx dist +``` + +`dist/` は静的ホストに置けます。公開用にまとめる際は、リポジトリ直下のライセンスと第三者表示を同梱してください。 diff --git a/web-src/build.mjs b/web-src/build.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0ffe11563b7c90a9adb39d54303a05e8f556d034 --- /dev/null +++ b/web-src/build.mjs @@ -0,0 +1,36 @@ +import { createReadStream, createWriteStream } from 'node:fs'; +import { cp, mkdir, stat } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { pipeline } from 'node:stream/promises'; +import { createGzip } from 'node:zlib'; +import { build } from 'esbuild'; + +const [modelPath, destination = 'dist'] = process.argv.slice(2); +if (!modelPath) throw new Error('Pass the folder produced by s0472_export_lite_onnx.py'); +const model = resolve(modelPath); +const output = resolve(destination); +const runtime = resolve(output, 'runtime'); +const packageDir = resolve('node_modules', 'onnxruntime-web'); +await mkdir(resolve(output, 'lite'), { recursive: true }); +await mkdir(runtime, { recursive: true }); +for (const filename of ['byte-network.onnx', 'role-network.onnx']) { + await pipeline(createReadStream(resolve(model, filename)), createGzip({ level: 9 }), + createWriteStream(resolve(output, 'lite', filename + '.gz'))); +} +await cp(resolve(model, 'model.json'), resolve(output, 'lite', 'model.json')); +await cp(resolve(packageDir, 'dist/ort-wasm-simd-threaded.mjs'), resolve(runtime, 'ort-wasm-simd-threaded.mjs')); +await pipeline(createReadStream(resolve(packageDir, 'dist/ort-wasm-simd-threaded.wasm')), createGzip({ level: 9 }), + createWriteStream(resolve(runtime, 'ort-wasm-simd-threaded.wasm.gz'))); +for (const filename of ['LICENSE', 'ThirdPartyNotices.txt']) { + const source = resolve(packageDir, filename); + if (await stat(source).catch(() => null)) await cp(source, resolve(runtime, filename)); +} +for (const filename of ['index.html', 'style.css']) await cp(filename, resolve(output, filename)); +await build({ + entryPoints: ['src/app.ts'], + outfile: resolve(output, 'app.js'), + bundle: true, + format: 'esm', + target: 'es2022', + minify: true, +}); diff --git a/web-src/index.html b/web-src/index.html new file mode 100644 index 0000000000000000000000000000000000000000..bec772ccf791cde86c854743bf97efeff45b548d --- /dev/null +++ b/web-src/index.html @@ -0,0 +1,43 @@ + + + + + + + Bibform + + + + +
+
+

Bibform

+

引用文をBibLaTeXに変換します。引用文の処理はブラウザ内で完結します。

+
+
+
+
+ + +
+ +

+
+
+ +
+
+ + +
+ +
+
+
+
+ + diff --git a/web-src/package-lock.json b/web-src/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..3bfa9b440bcbe999cb1da0d965d8262f58b86b5f --- /dev/null +++ b/web-src/package-lock.json @@ -0,0 +1,1015 @@ +{ + "name": "bibform-web", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "bibform-web", + "dependencies": { + "onnxruntime-web": "1.31.1" + }, + "devDependencies": { + "esbuild": "0.28.2", + "typescript": "7.0.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/onnxruntime-common": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz", + "integrity": "sha512-F+nnYNiQtmNJ95V6R/isBJqiVpdANCrsMEg1OaF+Bkbl3GAtzWLR7Ng17Ld0QtYtYJyotOHPJzOQn1Y6PLZjpg==", + "license": "MIT" + }, + "node_modules/onnxruntime-web": { + "version": "1.31.1", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.31.1.tgz", + "integrity": "sha512-5GeH+bWQ+HxM10z7erGlsWqryrwMbSvm/1tkIsKTT48g0fI19VXVVC435t4t7VsPdSQeS7NmuZPXrQ73k82URw==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.31.1", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + } + } +} diff --git a/web-src/package.json b/web-src/package.json new file mode 100644 index 0000000000000000000000000000000000000000..deaebad79a4bbdd686eaa322975cf148b6030dfa --- /dev/null +++ b/web-src/package.json @@ -0,0 +1,16 @@ +{ + "name": "bibform-web", + "private": true, + "type": "module", + "scripts": { + "build": "node build.mjs", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "onnxruntime-web": "1.31.1" + }, + "devDependencies": { + "esbuild": "0.28.2", + "typescript": "7.0.2" + } +} diff --git a/web-src/src/app.ts b/web-src/src/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..03567a05e2705cfa388f90268c0ae653da845a41 --- /dev/null +++ b/web-src/src/app.ts @@ -0,0 +1,107 @@ +import { makeBiblatex, TYPE_LABELS } from './biblatex'; +import { LiteModel, type Prediction } from './lite'; + +const form = document.querySelector('form'); +const source = document.querySelector('#source'); +const typeSelect = document.querySelector('#type'); +const output = document.querySelector('#output'); +const status = document.querySelector('#status'); +const choices = document.querySelector('#choices'); +const download = document.querySelector('#download'); +const submit = document.querySelector('#submit'); +const candidates = document.querySelector('#candidates'); +if (!(form instanceof HTMLFormElement) || !(source instanceof HTMLTextAreaElement) || + !(typeSelect instanceof HTMLSelectElement) || !(output instanceof HTMLTextAreaElement) || + !(status instanceof HTMLElement) || !(choices instanceof HTMLElement) || + !(download instanceof HTMLButtonElement) || !(submit instanceof HTMLButtonElement) || + !(candidates instanceof HTMLElement)) throw new Error('Bibform controls are missing'); + +let model: Promise | undefined; +let prediction: Prediction | undefined; +let original = ''; +let predicting = false; +const threshold = .90; +for (const [type, label] of TYPE_LABELS) typeSelect.add(new Option(`${label} · @${type}`, type)); + +function refreshOutput(): void { + if (!(typeSelect instanceof HTMLSelectElement) || !(output instanceof HTMLTextAreaElement) || + !(download instanceof HTMLButtonElement)) return; + output.value = prediction && typeSelect.value ? makeBiblatex(original, prediction, typeSelect.value) : ''; + download.disabled = !output.value; +} + +function chooseType(type: string): void { + if (!(typeSelect instanceof HTMLSelectElement) || !(status instanceof HTMLElement)) return; + typeSelect.value = type; + status.textContent = type ? `資料種別に「${TYPE_LABELS.get(type)}」を選びました。` + : '候補から資料種別を選んでください。'; + refreshOutput(); +} + +function renderCandidates(result: Prediction): void { + if (!(candidates instanceof HTMLElement) || !(typeSelect instanceof HTMLSelectElement) || + !(status instanceof HTMLElement)) return; + const first = result.candidates[0]; + const automatic = first.score >= threshold; + typeSelect.value = automatic ? first.type : ''; + status.textContent = automatic + ? `第1候補を選択しました(スコア ${(first.score * 100).toFixed(1)}%)。` + : '候補から資料種別を選んでください。'; + candidates.replaceChildren(); + if (!automatic) { + for (const item of result.candidates.slice(0, 3)) { + const button = document.createElement('button'); + button.type = 'button'; + button.textContent = `${TYPE_LABELS.get(item.type) ?? item.type} ${(item.score * 100).toFixed(1)}%`; + button.addEventListener('click', () => chooseType(item.type)); + candidates.append(button); + } + } +} + +form.addEventListener('submit', async (event) => { + event.preventDefault(); + if (predicting || !source.value.trim()) return; + original = source.value; + prediction = undefined; + refreshOutput(); + choices.hidden = true; + submit.disabled = true; + source.readOnly = true; + predicting = true; + status.textContent = model ? '解析中…' : '軽量版モデルを読み込み中…'; + try { + model ??= LiteModel.load(new URL('./lite/', document.baseURI)).catch((reason: unknown) => { + model = undefined; + throw reason; + }); + prediction = await (await model).predict(original); + renderCandidates(prediction); + choices.hidden = false; + refreshOutput(); + } catch (reason) { + console.error(reason); + status.textContent = '解析できませんでした。ページを再読み込みしてからお試しください。'; + } finally { + predicting = false; + source.readOnly = false; + submit.disabled = false; + } +}); + +source.addEventListener('input', () => { + prediction = undefined; + choices.hidden = true; + status.textContent = ''; + refreshOutput(); +}); +typeSelect.addEventListener('change', () => chooseType(typeSelect.value)); +download.addEventListener('click', () => { + if (!output.value) return; + const url = URL.createObjectURL(new Blob([output.value], { type: 'application/x-bibtex' })); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = 'reference.bib'; + anchor.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +}); diff --git a/web-src/src/biblatex.ts b/web-src/src/biblatex.ts new file mode 100644 index 0000000000000000000000000000000000000000..403571b00f0c9d7b1338a4de07931c24cb9b1373 --- /dev/null +++ b/web-src/src/biblatex.ts @@ -0,0 +1,57 @@ +import type { Prediction } from './lite'; + +export const TYPE_LABELS = new Map([ + ['article', '雑誌論文'], ['book', '書籍'], ['collection', '編著書'], + ['incollection', '書籍の章'], ['inproceedings', '会議論文'], ['misc', 'その他'], + ['online', 'ウェブ資料'], ['proceedings', '会議録'], ['thesis', '学位論文'], +]); + +const FIELD_NAMES = new Map([ + ['TITLE', 'title'], ['VOLUME', 'volume'], ['ISSUE', 'number'], ['PAGES', 'pages'], + ['DOI', 'doi'], ['ISBN', 'isbn'], ['URL', 'url'], ['EDITION', 'edition'], ['VERSION', 'version'], +]); + +const ESCAPES = new Map([ + ['\\', '\\textbackslash{}'], ['~', '\\textasciitilde{}'], ['^', '\\textasciicircum{}'], + ...Array.from('{}&#%$_', (symbol): [string, string] => [symbol, '\\' + symbol]), +]); + +function escapeTex(value: string): string { + return Array.from(value, (symbol) => ESCAPES.get(symbol) ?? symbol).join(''); +} + +export function makeBiblatex(source: string, prediction: Prediction, type: string): string { + if (!TYPE_LABELS.has(type)) throw new Error('資料種別を選んでください'); + const fields = new Map(); + for (const field of prediction.fields) { + if (!field.value) continue; + if (field.label === 'DATE') { + const name = /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/u.test(field.value) ? 'date' : 'note'; + fields.set(name, [fields.get(name), escapeTex(field.value)].filter(Boolean).join('. ')); + continue; + } + const name = field.label === 'CONTAINER_TITLE' ? type === 'article' ? 'journaltitle' : 'booktitle' + : field.label === 'ISSUER' ? type === 'thesis' ? 'institution' + : type === 'misc' || type === 'online' ? 'organization' : 'publisher' + : FIELD_NAMES.get(field.label); + if (name && !fields.has(name)) fields.set(name, escapeTex(field.value)); + } + const people = new Map>(); + for (const person of prediction.contributors) { + const family = person.nameParts.get('family')?.value; + const given = person.nameParts.get('given')?.value; + const name = family && given ? `{${escapeTex(family)}}, {${escapeTex(given)}}` + : `{${escapeTex(person.value)}}`; + for (const role of person.roles) { + const field = role === 'author.container' ? 'bookauthor' : role.split('.')[0]; + const names = people.get(field); + if (names) names.add(name); + else people.set(field, new Set([name])); + } + } + const entries = [...[...people].map(([role, names]) => [role, [...names].join(' and ')]), ...fields]; + let hash = 2166136261; + for (const character of source) hash = Math.imul(hash ^ (character.codePointAt(0) ?? 0), 16777619); + return [`@${type}{bibform-${(hash >>> 0).toString(16)},`, + ...entries.map(([key, value]) => ` ${key} = {${value}},`), '}'].join('\n') + '\n'; +} diff --git a/web-src/src/lite.ts b/web-src/src/lite.ts new file mode 100644 index 0000000000000000000000000000000000000000..9687a4a7a59aa39b945608acf50fb3a18375adb0 --- /dev/null +++ b/web-src/src/lite.ts @@ -0,0 +1,298 @@ +import { env, InferenceSession, Tensor } from 'onnxruntime-web/wasm'; + +interface Span { + start: number; + end: number; + value: string; +} + +interface Field extends Span { + label: string; +} + +interface Contributor extends Span { + kind: 'person' | 'organization'; + nameParts: Map; + roles: string[]; +} + +export interface TypeCandidate { + type: string; + score: number; +} + +export interface Prediction { + fields: Field[]; + contributors: Contributor[]; + candidates: TypeCandidate[]; +} + +interface ModelConfig { + outer: string[]; + names: string[]; + fields: string[]; + roles: string[]; + exportTypes: string[]; + ngrams: number[]; + buckets: number; + states: number[][]; + transitions: number[][]; + start: number[]; + end: number[]; +} + +function strings(value: unknown): string[] { + if (!Array.isArray(value) || !value.every((entry: unknown) => typeof entry === 'string')) { + throw new Error('Invalid model labels'); + } + return value; +} + +function numbers(value: unknown): number[] { + if (!Array.isArray(value) || !value.every((entry: unknown) => typeof entry === 'number' && Number.isFinite(entry))) { + throw new Error('Invalid model scores'); + } + return value; +} + +function matrix(value: unknown): number[][] { + if (!Array.isArray(value)) throw new Error('Invalid model matrix'); + return value.map(numbers); +} + +function parseConfig(value: unknown): ModelConfig { + if (!value || typeof value !== 'object' || + !('outer_labels' in value && 'name_labels' in value && 'fields' in value && 'roles' in value && + 'type_labels' in value && 'export_types' in value && 'ngrams' in value && 'buckets' in value && + 'states' in value && 'transitions' in value && 'start' in value && 'end' in value)) { + throw new Error('Invalid Bibform model config'); + } + const exportMap = value.export_types; + if (!exportMap || typeof exportMap !== 'object' || typeof value.buckets !== 'number' || + !Number.isSafeInteger(value.buckets) || value.buckets < 1) { + throw new Error('Invalid Bibform type mapping'); + } + const lookup = new Map(Object.entries(exportMap)); + const exportTypes = strings(value.type_labels).map((label): string => { + const type = lookup.get(label); + if (typeof type !== 'string') throw new Error('Missing BibLaTeX type'); + return type; + }); + const states = matrix(value.states); + const transitions = matrix(value.transitions); + const start = numbers(value.start); + const end = numbers(value.end); + const outer = strings(value.outer_labels); + const names = strings(value.name_labels); + const ngrams = numbers(value.ngrams); + if (!states.length || states.length >= 65536 || + states.some(([outerId, nameId]) => !Number.isInteger(outerId) || !Number.isInteger(nameId) || + outerId < 0 || outerId > 2 * outer.length || nameId < 0 || nameId > 2 * names.length) || + transitions.length !== states.length || transitions.some((row) => row.length !== states.length) || + start.length !== states.length || end.length !== states.length || + ngrams.some((n) => !Number.isSafeInteger(n) || n < 1)) { + throw new Error('Invalid Bibform decoder config'); + } + return { outer, names, fields: strings(value.fields), roles: strings(value.roles), + exportTypes, ngrams, buckets: value.buckets, states, transitions, start, end }; +} + +function ngramIds(characters: string[], config: ModelConfig): BigInt64Array { + const points = [1, ...characters.map((char) => (char.codePointAt(0) ?? 0) + 3), 2]; + const ids = new Set(); + for (const size of config.ngrams) { + for (let start = 0; start + size <= points.length; start++) { + let hash = size * 4099; + for (let index = start; index < start + size; index++) { + hash = Math.imul(hash ^ points[index], 16777619); + } + ids.add(((hash ^ (hash >>> 16)) >>> 0) % config.buckets); + } + } + return BigInt64Array.from(ids.size ? [...ids].sort((a, b) => a - b).map(BigInt) : [0n]); +} + +function byteIds(characters: string[]): BigInt64Array { + const output = new BigInt64Array(characters.length * 4); + const encoder = new TextEncoder(); + characters.forEach((char, index) => { + encoder.encode(char).forEach((byte, offset) => { + output[index * 4 + offset] = BigInt(byte + 1); + }); + }); + return output; +} + +function viterbi(outer: Float32Array, names: Float32Array, length: number, config: ModelConfig): number[] { + const count = config.states.length; + const outerWidth = 1 + 2 * config.outer.length; + const nameWidth = 1 + 2 * config.names.length; + const location = 1 + 2 * config.outer.indexOf('LOCATION'); + const scoreAt = (position: number, state: number): number => { + const [outerId, nameId] = config.states[state]; + const outerScore = outerId === location || outerId === location + 1 + ? -10000 : outer[position * outerWidth + outerId]; + return Math.fround(outerScore + names[position * nameWidth + nameId]); + }; + let scores = Float32Array.from(config.start, (start, index) => Math.fround(start + scoreAt(0, index))); + let next = new Float32Array(count); + const history = new Uint16Array(count * length); + for (let position = 1; position < length; position++) { + for (let current = 0; current < count; current++) { + let best = -Infinity; + let parent = 0; + for (let previous = 0; previous < count; previous++) { + const score = Math.fround(scores[previous] + config.transitions[previous][current]); + if (score > best) { + best = score; + parent = previous; + } + } + next[current] = Math.fround(best + scoreAt(position, current)); + history[position * count + current] = parent; + } + [scores, next] = [next, scores]; + } + let best = -Infinity; + let current = 0; + for (let state = 0; state < count; state++) { + const score = Math.fround(scores[state] + config.end[state]); + if (score > best) { + current = state; + best = score; + } + } + const path = new Array(length); + for (let position = length - 1; position >= 0; position--) { + path[position] = current; + current = history[position * count + current]; + } + return path; +} + +function bioSpans(indices: number[], labels: string[]): [string, number, number][] { + const spans: [string, number, number][] = []; + let active: string | undefined; + let start = 0; + [...indices, 0].forEach((index, position) => { + const label = index ? labels[Math.floor((index - 1) / 2)] : undefined; + if (active && (active !== label || index % 2 === 1)) { + spans.push([active, start, position]); + active = undefined; + } + if (label && !active) { + active = label; + start = position; + } + }); + return spans; +} + +function visibleValue(characters: string[], start: number, end: number, label: string): string { + const value = characters.slice(start, end).join('') + .replace(/[\p{White_Space}\u001c-\u001f]+/gu, ' ').replace(/^ | $/g, ''); + return ['DOI', 'URL', 'ISBN'].includes(label) ? value.normalize('NFKC') : value; +} + +function trim(characters: string[], span: Span): boolean { + const whitespace = /^[\p{White_Space}\u001c-\u001f]$/u; + while (span.start < span.end && whitespace.test(characters[span.start])) span.start++; + while (span.end > span.start && whitespace.test(characters[span.end - 1])) span.end--; + return span.start < span.end; +} + +function floatOutput(tensor: Tensor): Float32Array { + const { data } = tensor; + if (!(data instanceof Float32Array)) throw new Error('Invalid Bibform output scores'); + return data; +} + +async function loadBinary(url: URL): Promise { + const response = await fetch(url); + if (!response.ok) throw new Error('軽量版の実行ファイルを読み込めません'); + const body = await response.arrayBuffer(); + const marker = new Uint8Array(body, 0, Math.min(2, body.byteLength)); + if (marker[0] !== 0x1f || marker[1] !== 0x8b) return body; + const decoded = new Blob([body]).stream().pipeThrough(new DecompressionStream('gzip')); + return new Response(decoded).arrayBuffer(); +} + +export class LiteModel { + private constructor(private readonly config: ModelConfig, private readonly core: InferenceSession, + private readonly roleNetwork: InferenceSession) {} + + static async load(base: URL): Promise { + env.wasm.numThreads = 1; + const runtime = new URL('../runtime/', base); + env.wasm.wasmPaths = runtime.href; + const [configResponse, wasm, coreBytes, roleBytes] = await Promise.all([ + fetch(new URL('model.json', base)), + loadBinary(new URL('ort-wasm-simd-threaded.wasm.gz', runtime)), + loadBinary(new URL('byte-network.onnx.gz', base)), + loadBinary(new URL('role-network.onnx.gz', base)), + ]); + if (!configResponse.ok) throw new Error('軽量版のモデル設定を読み込めません'); + const config = parseConfig(await configResponse.json()); + env.wasm.wasmBinary = wasm; + const options = { executionProviders: ['wasm'] }; + const core = await InferenceSession.create(coreBytes, options); + const roles = await InferenceSession.create(roleBytes, options); + return new LiteModel(config, core, roles); + } + + async predict(text: string): Promise { + const characters = Array.from(text); + if (!characters.length) throw new Error('引用を入力してください'); + const { config } = this; + const grams = ngramIds(characters, config); + const feeds = { + bytes: new Tensor('int64', byteIds(characters), [1, characters.length, 4]), + ngrams: new Tensor('int64', grams, [grams.length]), + }; + const { outer, names, hidden, type_probabilities } = await this.core.run(feeds); + const path = viterbi(floatOutput(outer), floatOutput(names), characters.length, config); + const fields: Field[] = []; + const contributors: Contributor[] = []; + const outerSpans = bioSpans(path.map((index) => config.states[index][0]), config.outer); + const nameSpans = bioSpans(path.map((index) => config.states[index][1]), config.names); + for (const [label, start, end] of outerSpans) { + const span = { start, end, value: visibleValue(characters, start, end, label) }; + if (config.fields.includes(label)) { + fields.push({ label, ...span }); + } else if (label === 'organization' || label === 'person') { + const nameParts = new Map(); + if (label === 'person') { + for (const [name, left, right] of nameSpans) { + if (start <= left && right <= end && !nameParts.has(name)) { + nameParts.set(name, { start: left, end: right, value: visibleValue(characters, left, right, name) }); + } + } + if (!nameParts.size) continue; + } + contributors.push({ kind: label, ...span, nameParts, roles: [] }); + } + } + if (contributors.length) { + const starts = BigInt64Array.from(contributors.map((span) => BigInt(span.start))); + const ends = BigInt64Array.from(contributors.map((span) => BigInt(span.end))); + const { roles } = await this.roleNetwork.run({ hidden, + starts: new Tensor('int64', starts, [starts.length]), ends: new Tensor('int64', ends, [ends.length]) }); + const masks = floatOutput(roles); + contributors.forEach((person, index) => { + person.roles = config.roles.filter((_, offset) => masks[index * config.roles.length + offset]).sort(); + for (const [key, part] of person.nameParts) { + if (!trim(characters, part)) person.nameParts.delete(key); + } + }); + } + const totals = new Map(); + floatOutput(type_probabilities).forEach((score, index) => { + const type = config.exportTypes[index]; + totals.set(type, Math.fround((totals.get(type) ?? 0) + score)); + }); + const candidates = [...totals].map(([type, score]) => ({ type, score })) + .sort((left, right) => right.score - left.score || left.type.localeCompare(right.type, 'en')); + return { fields: fields.filter((field) => trim(characters, field)), + contributors: contributors.filter((person) => trim(characters, person)), candidates }; + } +} diff --git a/web-src/style.css b/web-src/style.css new file mode 100644 index 0000000000000000000000000000000000000000..221681bcac1eb5e2dfe5325979f74794f2444580 --- /dev/null +++ b/web-src/style.css @@ -0,0 +1,129 @@ +:root { + color: #172a32; + background: #f3f6f4; + font: 16px/1.6 system-ui, sans-serif; +} + +body { + margin: 0; +} + +main { + width: min(68rem, calc(100% - 3rem)); + margin: clamp(2rem, 6vw, 5rem) auto; +} + +header { + margin-block-end: 2rem; +} + +h1 { + margin: 0; + font-size: clamp(2rem, 5vw, 3.5rem); + line-height: 1.1; + letter-spacing: -.045em; +} + +header p { + margin: .7rem 0 0; + color: #3c545d; +} + +.columns { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.15rem; +} + +.columns > section { + padding: clamp(1rem, 3vw, 1.6rem); + border: 1px solid #cad9d3; + border-radius: 1rem; + background: white; +} + +label { + display: block; + margin-block-end: .35rem; + font-weight: 650; +} + +textarea, select, button { + font: inherit; + color: inherit; +} + +textarea, select { + box-sizing: border-box; + width: 100%; + border: 1px solid #829a94; + border-radius: .55rem; + background: #fcfdfc; + padding: .8rem; +} + +textarea { + display: block; + resize: vertical; +} + +#output { + font: .95rem/1.68 ui-monospace, monospace; +} + +button { + border: 1px solid #829a94; + border-radius: .55rem; + padding: .55rem .85rem; + background: white; + cursor: pointer; +} + +button.primary { + border-color: #115745; + background: #115745; + color: white; + font-weight: 650; +} + +button:disabled { + opacity: .6; + cursor: default; +} + +:focus-visible { + outline: 3px solid #177969; + outline-offset: 3px; +} + +.actions, #candidates { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .55rem; + margin-block-start: .85rem; +} + +#status { + margin: 0; + color: #3c545d; + font-size: .94rem; +} + +#choices { + margin-block-start: 1rem; +} + +#candidates:not(:empty) { + margin-block-end: .75rem; +} + +@media (max-width: 44rem) { + main { + width: calc(100% - 2rem); + } + + .columns { + grid-template-columns: 1fr; + } +} diff --git a/web-src/tsconfig.json b/web-src/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..dfd4fe396222827cd6f7d7c6d3a1cb91063614e5 --- /dev/null +++ b/web-src/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true + }, + "include": ["src/**/*.ts"] +}