Transformers
Safetensors
t5
text2text-generation
protein-language-model
fastplms
custom_code
text-generation-inference
Instructions to use Synthyra/ANKH2_large with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/ANKH2_large with Transformers:
# Load model directly from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("Synthyra/ANKH2_large", trust_remote_code=True) model = AutoModelForSeq2SeqLM.from_pretrained("Synthyra/ANKH2_large", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update FastPLMs runtime files
Browse filesAtomic FastPLMs complete publication. Checkpoint weights, tokenizer assets, runtime sources, model card, legal texts, and scoped attestations are updated together. Deletes are restricted to obsolete current-registry-pinned paths.
- LICENSES/FastPLMs-Apache-2.0.txt +203 -0
- LICENSES/ankh/LICENSE.md +353 -0
- README.md +244 -153
- THIRD_PARTY_NOTICES.md +99 -0
- artifact-manifest.json +35 -0
- config.json +31 -8
- fastplms/__init__.py +48 -0
- fastplms/attention/__init__.py +63 -0
- fastplms/attention/_core.py +779 -0
- fastplms/attention/_kernel_lock.py +191 -0
- fastplms/attention/interfaces.py +242 -0
- fastplms/embeddings/__init__.py +65 -0
- fastplms/embeddings/pooling.py +210 -0
- fastplms/embeddings/runner.py +1559 -0
- fastplms/embeddings/storage.py +1594 -0
- fastplms/embeddings/types.py +187 -0
- fastplms/models.toml +1223 -0
- fastplms/models/__init__.py +10 -0
- fastplms/models/ankh/__init__.py +0 -0
- fastplms/models/ankh/modeling_ankh.py +1627 -0
- fastplms/models/ttt.py +866 -0
- fastplms/registry.py +1486 -0
- fastplms/runtime.py +68 -0
- fastplms_bundle.py +0 -0
- generation_config.json +7 -0
- model.safetensors → model-00001-of-00002.safetensors +2 -2
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +783 -0
- modeling_fastplms.py +238 -0
- provenance.json +165 -0
- runtime-attestation.json +45 -0
- special_tokens_map.json +4 -28
- tokenizer.json +2 -4
-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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PLEASE NOTE THE APACHE LICENSE ONLY APPLIES TO THE CODE IN THE FastPLMs GITHUB AND ASSOCIATED HUGGINGFACE REPOSITORIES, NOT NECESSARILY THE MODEL WEIGHTS. THOSE LICENSES CAN BE FOUND HERE https://github.com/Synthyra/FastPLMs/tree/main/LICENSES
|
| 2 |
+
|
| 3 |
+
Apache License
|
| 4 |
+
Version 2.0, January 2004
|
| 5 |
+
http://www.apache.org/licenses/
|
| 6 |
+
|
| 7 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 8 |
+
|
| 9 |
+
1. Definitions.
|
| 10 |
+
|
| 11 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 12 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 13 |
+
|
| 14 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 15 |
+
the copyright owner that is granting the License.
|
| 16 |
+
|
| 17 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 18 |
+
other entities that control, are controlled by, or are under common
|
| 19 |
+
control with that entity. For the purposes of this definition,
|
| 20 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 21 |
+
direction or management of such entity, whether by contract or
|
| 22 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 23 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 24 |
+
|
| 25 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 26 |
+
exercising permissions granted by this License.
|
| 27 |
+
|
| 28 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 29 |
+
including but not limited to software source code, documentation
|
| 30 |
+
source, and configuration files.
|
| 31 |
+
|
| 32 |
+
"Object" form shall mean any form resulting from mechanical
|
| 33 |
+
transformation or translation of a Source form, including but
|
| 34 |
+
not limited to compiled object code, generated documentation,
|
| 35 |
+
and conversions to other media types.
|
| 36 |
+
|
| 37 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 38 |
+
Object form, made available under the License, as indicated by a
|
| 39 |
+
copyright notice that is included in or attached to the work
|
| 40 |
+
(an example is provided in the Appendix below).
|
| 41 |
+
|
| 42 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 43 |
+
form, that is based on (or derived from) the Work and for which the
|
| 44 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 45 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 46 |
+
of this License, Derivative Works shall not include works that remain
|
| 47 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 48 |
+
the Work and Derivative Works thereof.
|
| 49 |
+
|
| 50 |
+
"Contribution" shall mean any work of authorship, including
|
| 51 |
+
the original version of the Work and any modifications or additions
|
| 52 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 53 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 54 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 55 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 56 |
+
means any form of electronic, verbal, or written communication sent
|
| 57 |
+
to the Licensor or its representatives, including but not limited to
|
| 58 |
+
communication on electronic mailing lists, source code control systems,
|
| 59 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 60 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 61 |
+
excluding communication that is conspicuously marked or otherwise
|
| 62 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 63 |
+
|
| 64 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 65 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 66 |
+
subsequently incorporated within the Work.
|
| 67 |
+
|
| 68 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 69 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 70 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 71 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 72 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 73 |
+
Work and such Derivative Works in Source or Object form.
|
| 74 |
+
|
| 75 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 76 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 77 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 78 |
+
(except as stated in this section) patent license to make, have made,
|
| 79 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 80 |
+
where such license applies only to those patent claims licensable
|
| 81 |
+
by such Contributor that are necessarily infringed by their
|
| 82 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 83 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 84 |
+
institute patent litigation against any entity (including a
|
| 85 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 86 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 87 |
+
or contributory patent infringement, then any patent licenses
|
| 88 |
+
granted to You under this License for that Work shall terminate
|
| 89 |
+
as of the date such litigation is filed.
|
| 90 |
+
|
| 91 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 92 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 93 |
+
modifications, and in Source or Object form, provided that You
|
| 94 |
+
meet the following conditions:
|
| 95 |
+
|
| 96 |
+
(a) You must give any other recipients of the Work or
|
| 97 |
+
Derivative Works a copy of this License; and
|
| 98 |
+
|
| 99 |
+
(b) You must cause any modified files to carry prominent notices
|
| 100 |
+
stating that You changed the files; and
|
| 101 |
+
|
| 102 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 103 |
+
that You distribute, all copyright, patent, trademark, and
|
| 104 |
+
attribution notices from the Source form of the Work,
|
| 105 |
+
excluding those notices that do not pertain to any part of
|
| 106 |
+
the Derivative Works; and
|
| 107 |
+
|
| 108 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 109 |
+
distribution, then any Derivative Works that You distribute must
|
| 110 |
+
include a readable copy of the attribution notices contained
|
| 111 |
+
within such NOTICE file, excluding those notices that do not
|
| 112 |
+
pertain to any part of the Derivative Works, in at least one
|
| 113 |
+
of the following places: within a NOTICE text file distributed
|
| 114 |
+
as part of the Derivative Works; within the Source form or
|
| 115 |
+
documentation, if provided along with the Derivative Works; or,
|
| 116 |
+
within a display generated by the Derivative Works, if and
|
| 117 |
+
wherever such third-party notices normally appear. The contents
|
| 118 |
+
of the NOTICE file are for informational purposes only and
|
| 119 |
+
do not modify the License. You may add Your own attribution
|
| 120 |
+
notices within Derivative Works that You distribute, alongside
|
| 121 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 122 |
+
that such additional attribution notices cannot be construed
|
| 123 |
+
as modifying the License.
|
| 124 |
+
|
| 125 |
+
You may add Your own copyright statement to Your modifications and
|
| 126 |
+
may provide additional or different license terms and conditions
|
| 127 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 128 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 129 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 130 |
+
the conditions stated in this License.
|
| 131 |
+
|
| 132 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 133 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 134 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 135 |
+
this License, without any additional terms or conditions.
|
| 136 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 137 |
+
the terms of any separate license agreement you may have executed
|
| 138 |
+
with Licensor regarding such Contributions.
|
| 139 |
+
|
| 140 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 141 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 142 |
+
except as required for reasonable and customary use in describing the
|
| 143 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 144 |
+
|
| 145 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 146 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 147 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 148 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 149 |
+
implied, including, without limitation, any warranties or conditions
|
| 150 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 151 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 152 |
+
appropriateness of using or redistributing the Work and assume any
|
| 153 |
+
risks associated with Your exercise of permissions under this License.
|
| 154 |
+
|
| 155 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 156 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 157 |
+
unless required by applicable law (such as deliberate and grossly
|
| 158 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 159 |
+
liable to You for damages, including any direct, indirect, special,
|
| 160 |
+
incidental, or consequential damages of any character arising as a
|
| 161 |
+
result of this License or out of the use or inability to use the
|
| 162 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 163 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 164 |
+
other commercial damages or losses), even if such Contributor
|
| 165 |
+
has been advised of the possibility of such damages.
|
| 166 |
+
|
| 167 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 168 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 169 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 170 |
+
or other liability obligations and/or rights consistent with this
|
| 171 |
+
License. However, in accepting such obligations, You may act only
|
| 172 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 173 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 174 |
+
defend, and hold each Contributor harmless for any liability
|
| 175 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 176 |
+
of your accepting any such warranty or additional liability.
|
| 177 |
+
|
| 178 |
+
END OF TERMS AND CONDITIONS
|
| 179 |
+
|
| 180 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 181 |
+
|
| 182 |
+
To apply the Apache License to your work, attach the following
|
| 183 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 184 |
+
replaced with your own identifying information. (Don't include
|
| 185 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 186 |
+
comment syntax for the file format. We also recommend that a
|
| 187 |
+
file or class name and description of purpose be included on the
|
| 188 |
+
same "printed page" as the copyright notice for easier
|
| 189 |
+
identification within third-party archives.
|
| 190 |
+
|
| 191 |
+
Copyright [yyyy] [name of copyright owner]
|
| 192 |
+
|
| 193 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 194 |
+
you may not use this file except in compliance with the License.
|
| 195 |
+
You may obtain a copy of the License at
|
| 196 |
+
|
| 197 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 198 |
+
|
| 199 |
+
Unless required by applicable law or agreed to in writing, software
|
| 200 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 201 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 202 |
+
See the License for the specific language governing permissions and
|
| 203 |
+
limitations under the License.
|
LICENSES/ankh/LICENSE.md
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
| 2 |
+
|
| 3 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 4 |
+
does not provide legal services or legal advice. Distribution of
|
| 5 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 6 |
+
other relationship. Creative Commons makes its licenses and related
|
| 7 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 8 |
+
warranties regarding its licenses, any material licensed under their
|
| 9 |
+
terms and conditions, or any related information. Creative Commons
|
| 10 |
+
disclaims all liability for damages resulting from their use to the
|
| 11 |
+
fullest extent possible.
|
| 12 |
+
|
| 13 |
+
Using Creative Commons Public Licenses
|
| 14 |
+
|
| 15 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 16 |
+
conditions that creators and other rights holders may use to share
|
| 17 |
+
original works of authorship and other material subject to copyright and
|
| 18 |
+
certain other rights specified in the public license below. The
|
| 19 |
+
following considerations are for informational purposes only, are not
|
| 20 |
+
exhaustive, and do not form part of our licenses.
|
| 21 |
+
|
| 22 |
+
Considerations for licensors: Our public licenses are intended for use
|
| 23 |
+
by those authorized to give the public permission to use material in
|
| 24 |
+
ways otherwise restricted by copyright and certain other rights. Our
|
| 25 |
+
licenses are irrevocable. Licensors should read and understand the terms
|
| 26 |
+
and conditions of the license they choose before applying it. Licensors
|
| 27 |
+
should also secure all rights necessary before applying our licenses so
|
| 28 |
+
that the public can reuse the material as expected. Licensors should
|
| 29 |
+
clearly mark any material not subject to the license. This includes
|
| 30 |
+
other CC-licensed material, or material used under an exception or
|
| 31 |
+
limitation to copyright. More considerations for licensors :
|
| 32 |
+
wiki.creativecommons.org/Considerations\_for\_licensors
|
| 33 |
+
|
| 34 |
+
Considerations for the public: By using one of our public licenses, a
|
| 35 |
+
licensor grants the public permission to use the licensed material under
|
| 36 |
+
specified terms and conditions. If the licensor's permission is not
|
| 37 |
+
necessary for any reason–for example, because of any applicable
|
| 38 |
+
exception or limitation to copyright–then that use is not regulated by
|
| 39 |
+
the license. Our licenses grant only permissions under copyright and
|
| 40 |
+
certain other rights that a licensor has authority to grant. Use of the
|
| 41 |
+
licensed material may still be restricted for other reasons, including
|
| 42 |
+
because others have copyright or other rights in the material. A
|
| 43 |
+
licensor may make special requests, such as asking that all changes be
|
| 44 |
+
marked or described. Although not required by our licenses, you are
|
| 45 |
+
encouraged to respect those requests where reasonable. More
|
| 46 |
+
considerations for the public :
|
| 47 |
+
wiki.creativecommons.org/Considerations\_for\_licensees
|
| 48 |
+
|
| 49 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
| 50 |
+
Public License
|
| 51 |
+
|
| 52 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 53 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 54 |
+
Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
| 55 |
+
("Public License"). To the extent this Public License may be interpreted
|
| 56 |
+
as a contract, You are granted the Licensed Rights in consideration of
|
| 57 |
+
Your acceptance of these terms and conditions, and the Licensor grants
|
| 58 |
+
You such rights in consideration of benefits the Licensor receives from
|
| 59 |
+
making the Licensed Material available under these terms and conditions.
|
| 60 |
+
|
| 61 |
+
Section 1 – Definitions.
|
| 62 |
+
|
| 63 |
+
- a. Adapted Material means material subject to Copyright and Similar
|
| 64 |
+
Rights that is derived from or based upon the Licensed Material and
|
| 65 |
+
in which the Licensed Material is translated, altered, arranged,
|
| 66 |
+
transformed, or otherwise modified in a manner requiring permission
|
| 67 |
+
under the Copyright and Similar Rights held by the Licensor. For
|
| 68 |
+
purposes of this Public License, where the Licensed Material is a
|
| 69 |
+
musical work, performance, or sound recording, Adapted Material is
|
| 70 |
+
always produced where the Licensed Material is synched in timed
|
| 71 |
+
relation with a moving image.
|
| 72 |
+
- b. Adapter's License means the license You apply to Your Copyright
|
| 73 |
+
and Similar Rights in Your contributions to Adapted Material in
|
| 74 |
+
accordance with the terms and conditions of this Public License.
|
| 75 |
+
- c. BY-NC-SA Compatible License means a license listed at
|
| 76 |
+
creativecommons.org/compatiblelicenses, approved by Creative Commons
|
| 77 |
+
as essentially the equivalent of this Public License.
|
| 78 |
+
- d. Copyright and Similar Rights means copyright and/or similar
|
| 79 |
+
rights closely related to copyright including, without limitation,
|
| 80 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 81 |
+
Rights, without regard to how the rights are labeled or categorized.
|
| 82 |
+
For purposes of this Public License, the rights specified in Section
|
| 83 |
+
2(b)(1)-(2) are not Copyright and Similar Rights.
|
| 84 |
+
- e. Effective Technological Measures means those measures that, in
|
| 85 |
+
the absence of proper authority, may not be circumvented under laws
|
| 86 |
+
fulfilling obligations under Article 11 of the WIPO Copyright Treaty
|
| 87 |
+
adopted on December 20, 1996, and/or similar international
|
| 88 |
+
agreements.
|
| 89 |
+
- f. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 90 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 91 |
+
that applies to Your use of the Licensed Material.
|
| 92 |
+
- g. License Elements means the license attributes listed in the name
|
| 93 |
+
of a Creative Commons Public License. The License Elements of this
|
| 94 |
+
Public License are Attribution, NonCommercial, and ShareAlike.
|
| 95 |
+
- h. Licensed Material means the artistic or literary work, database,
|
| 96 |
+
or other material to which the Licensor applied this Public License.
|
| 97 |
+
- i. Licensed Rights means the rights granted to You subject to the
|
| 98 |
+
terms and conditions of this Public License, which are limited to
|
| 99 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 100 |
+
Licensed Material and that the Licensor has authority to license.
|
| 101 |
+
- j. Licensor means the individual(s) or entity(ies) granting rights
|
| 102 |
+
under this Public License.
|
| 103 |
+
- k. NonCommercial means not primarily intended for or directed
|
| 104 |
+
towards commercial advantage or monetary compensation. For purposes
|
| 105 |
+
of this Public License, the exchange of the Licensed Material for
|
| 106 |
+
other material subject to Copyright and Similar Rights by digital
|
| 107 |
+
file-sharing or similar means is NonCommercial provided there is no
|
| 108 |
+
payment of monetary compensation in connection with the exchange.
|
| 109 |
+
- l. Share means to provide material to the public by any means or
|
| 110 |
+
process that requires permission under the Licensed Rights, such as
|
| 111 |
+
reproduction, public display, public performance, distribution,
|
| 112 |
+
dissemination, communication, or importation, and to make material
|
| 113 |
+
available to the public including in ways that members of the public
|
| 114 |
+
may access the material from a place and at a time individually
|
| 115 |
+
chosen by them.
|
| 116 |
+
- m. Sui Generis Database Rights means rights other than copyright
|
| 117 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 118 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 119 |
+
as amended and/or succeeded, as well as other essentially equivalent
|
| 120 |
+
rights anywhere in the world.
|
| 121 |
+
- n. You means the individual or entity exercising the Licensed Rights
|
| 122 |
+
under this Public License. Your has a corresponding meaning.
|
| 123 |
+
|
| 124 |
+
Section 2 – Scope.
|
| 125 |
+
|
| 126 |
+
- a. License grant.
|
| 127 |
+
- 1. Subject to the terms and conditions of this Public License,
|
| 128 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 129 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 130 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 131 |
+
- A. reproduce and Share the Licensed Material, in whole or in
|
| 132 |
+
part, for NonCommercial purposes only; and
|
| 133 |
+
- B. produce, reproduce, and Share Adapted Material for
|
| 134 |
+
NonCommercial purposes only.
|
| 135 |
+
- 2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 136 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 137 |
+
License does not apply, and You do not need to comply with its
|
| 138 |
+
terms and conditions.
|
| 139 |
+
- 3. Term. The term of this Public License is specified in Section
|
| 140 |
+
6(a).
|
| 141 |
+
- 4. Media and formats; technical modifications allowed. The
|
| 142 |
+
Licensor authorizes You to exercise the Licensed Rights in all
|
| 143 |
+
media and formats whether now known or hereafter created, and to
|
| 144 |
+
make technical modifications necessary to do so. The Licensor
|
| 145 |
+
waives and/or agrees not to assert any right or authority to
|
| 146 |
+
forbid You from making technical modifications necessary to
|
| 147 |
+
exercise the Licensed Rights, including technical modifications
|
| 148 |
+
necessary to circumvent Effective Technological Measures. For
|
| 149 |
+
purposes of this Public License, simply making modifications
|
| 150 |
+
authorized by this Section 2(a)(4) never produces Adapted
|
| 151 |
+
Material.
|
| 152 |
+
- 5. Downstream recipients.
|
| 153 |
+
- A. Offer from the Licensor – Licensed Material. Every
|
| 154 |
+
recipient of the Licensed Material automatically receives an
|
| 155 |
+
offer from the Licensor to exercise the Licensed Rights
|
| 156 |
+
under the terms and conditions of this Public License.
|
| 157 |
+
- B. Additional offer from the Licensor – Adapted Material.
|
| 158 |
+
Every recipient of Adapted Material from You automatically
|
| 159 |
+
receives an offer from the Licensor to exercise the Licensed
|
| 160 |
+
Rights in the Adapted Material under the conditions of the
|
| 161 |
+
Adapter's License You apply.
|
| 162 |
+
- C. No downstream restrictions. You may not offer or impose
|
| 163 |
+
any additional or different terms or conditions on, or apply
|
| 164 |
+
any Effective Technological Measures to, the Licensed
|
| 165 |
+
Material if doing so restricts exercise of the Licensed
|
| 166 |
+
Rights by any recipient of the Licensed Material.
|
| 167 |
+
- 6. No endorsement. Nothing in this Public License constitutes or
|
| 168 |
+
may be construed as permission to assert or imply that You are,
|
| 169 |
+
or that Your use of the Licensed Material is, connected with, or
|
| 170 |
+
sponsored, endorsed, or granted official status by, the Licensor
|
| 171 |
+
or others designated to receive attribution as provided in
|
| 172 |
+
Section 3(a)(1)(A)(i).
|
| 173 |
+
- b. Other rights.
|
| 174 |
+
- 1. Moral rights, such as the right of integrity, are not
|
| 175 |
+
licensed under this Public License, nor are publicity, privacy,
|
| 176 |
+
and/or other similar personality rights; however, to the extent
|
| 177 |
+
possible, the Licensor waives and/or agrees not to assert any
|
| 178 |
+
such rights held by the Licensor to the limited extent necessary
|
| 179 |
+
to allow You to exercise the Licensed Rights, but not otherwise.
|
| 180 |
+
- 2. Patent and trademark rights are not licensed under this
|
| 181 |
+
Public License.
|
| 182 |
+
- 3. To the extent possible, the Licensor waives any right to
|
| 183 |
+
collect royalties from You for the exercise of the Licensed
|
| 184 |
+
Rights, whether directly or through a collecting society under
|
| 185 |
+
any voluntary or waivable statutory or compulsory licensing
|
| 186 |
+
scheme. In all other cases the Licensor expressly reserves any
|
| 187 |
+
right to collect such royalties, including when the Licensed
|
| 188 |
+
Material is used other than for NonCommercial purposes.
|
| 189 |
+
|
| 190 |
+
Section 3 – License Conditions.
|
| 191 |
+
|
| 192 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 193 |
+
following conditions.
|
| 194 |
+
|
| 195 |
+
- a. Attribution.
|
| 196 |
+
- 1. If You Share the Licensed Material (including in modified
|
| 197 |
+
form), You must:
|
| 198 |
+
- A. retain the following if it is supplied by the Licensor
|
| 199 |
+
with the Licensed Material:
|
| 200 |
+
- i. identification of the creator(s) of the Licensed
|
| 201 |
+
Material and any others designated to receive
|
| 202 |
+
attribution, in any reasonable manner requested by the
|
| 203 |
+
Licensor (including by pseudonym if designated);
|
| 204 |
+
- ii. a copyright notice;
|
| 205 |
+
- iii. a notice that refers to this Public License;
|
| 206 |
+
- iv. a notice that refers to the disclaimer of
|
| 207 |
+
warranties;
|
| 208 |
+
- v. a URI or hyperlink to the Licensed Material to the
|
| 209 |
+
extent reasonably practicable;
|
| 210 |
+
|
| 211 |
+
- B. indicate if You modified the Licensed Material and retain
|
| 212 |
+
an indication of any previous modifications; and
|
| 213 |
+
- C. indicate the Licensed Material is licensed under this
|
| 214 |
+
Public License, and include the text of, or the URI or
|
| 215 |
+
hyperlink to, this Public License.
|
| 216 |
+
- 2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 217 |
+
reasonable manner based on the medium, means, and context in
|
| 218 |
+
which You Share the Licensed Material. For example, it may be
|
| 219 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 220 |
+
hyperlink to a resource that includes the required information.
|
| 221 |
+
- 3. If requested by the Licensor, You must remove any of the
|
| 222 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 223 |
+
reasonably practicable.
|
| 224 |
+
- b. ShareAlike.In addition to the conditions in Section 3(a), if You
|
| 225 |
+
Share Adapted Material You produce, the following conditions also
|
| 226 |
+
apply.
|
| 227 |
+
- 1. The Adapter's License You apply must be a Creative Commons
|
| 228 |
+
license with the same License Elements, this version or later,
|
| 229 |
+
or a BY-NC-SA Compatible License.
|
| 230 |
+
- 2. You must include the text of, or the URI or hyperlink to, the
|
| 231 |
+
Adapter's License You apply. You may satisfy this condition in
|
| 232 |
+
any reasonable manner based on the medium, means, and context in
|
| 233 |
+
which You Share Adapted Material.
|
| 234 |
+
- 3. You may not offer or impose any additional or different terms
|
| 235 |
+
or conditions on, or apply any Effective Technological Measures
|
| 236 |
+
to, Adapted Material that restrict exercise of the rights
|
| 237 |
+
granted under the Adapter's License You apply.
|
| 238 |
+
|
| 239 |
+
Section 4 – Sui Generis Database Rights.
|
| 240 |
+
|
| 241 |
+
Where the Licensed Rights include Sui Generis Database Rights that apply
|
| 242 |
+
to Your use of the Licensed Material:
|
| 243 |
+
|
| 244 |
+
- a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 245 |
+
to extract, reuse, reproduce, and Share all or a substantial portion
|
| 246 |
+
of the contents of the database for NonCommercial purposes only;
|
| 247 |
+
- b. if You include all or a substantial portion of the database
|
| 248 |
+
contents in a database in which You have Sui Generis Database
|
| 249 |
+
Rights, then the database in which You have Sui Generis Database
|
| 250 |
+
Rights (but not its individual contents) is Adapted Material,
|
| 251 |
+
including for purposes of Section 3(b); and
|
| 252 |
+
- c. You must comply with the conditions in Section 3(a) if You Share
|
| 253 |
+
all or a substantial portion of the contents of the database.
|
| 254 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 255 |
+
replace Your obligations under this Public License where the
|
| 256 |
+
Licensed Rights include other Copyright and Similar Rights.
|
| 257 |
+
|
| 258 |
+
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
| 259 |
+
|
| 260 |
+
- a. Unless otherwise separately undertaken by the Licensor, to the
|
| 261 |
+
extent possible, the Licensor offers the Licensed Material as-is and
|
| 262 |
+
as-available, and makes no representations or warranties of any kind
|
| 263 |
+
concerning the Licensed Material, whether express, implied,
|
| 264 |
+
statutory, or other. This includes, without limitation, warranties
|
| 265 |
+
of title, merchantability, fitness for a particular purpose,
|
| 266 |
+
non-infringement, absence of latent or other defects, accuracy, or
|
| 267 |
+
the presence or absence of errors, whether or not known or
|
| 268 |
+
discoverable. Where disclaimers of warranties are not allowed in
|
| 269 |
+
full or in part, this disclaimer may not apply to You.
|
| 270 |
+
- b. To the extent possible, in no event will the Licensor be liable
|
| 271 |
+
to You on any legal theory (including, without limitation,
|
| 272 |
+
negligence) or otherwise for any direct, special, indirect,
|
| 273 |
+
incidental, consequential, punitive, exemplary, or other losses,
|
| 274 |
+
costs, expenses, or damages arising out of this Public License or
|
| 275 |
+
use of the Licensed Material, even if the Licensor has been advised
|
| 276 |
+
of the possibility of such losses, costs, expenses, or damages.
|
| 277 |
+
Where a limitation of liability is not allowed in full or in part,
|
| 278 |
+
this limitation may not apply to You.
|
| 279 |
+
- c. The disclaimer of warranties and limitation of liability provided
|
| 280 |
+
above shall be interpreted in a manner that, to the extent possible,
|
| 281 |
+
most closely approximates an absolute disclaimer and waiver of all
|
| 282 |
+
liability.
|
| 283 |
+
|
| 284 |
+
Section 6 – Term and Termination.
|
| 285 |
+
|
| 286 |
+
- a. This Public License applies for the term of the Copyright and
|
| 287 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 288 |
+
this Public License, then Your rights under this Public License
|
| 289 |
+
terminate automatically.
|
| 290 |
+
- b. Where Your right to use the Licensed Material has terminated
|
| 291 |
+
under Section 6(a), it reinstates:
|
| 292 |
+
|
| 293 |
+
- 1. automatically as of the date the violation is cured, provided
|
| 294 |
+
it is cured within 30 days of Your discovery of the violation;
|
| 295 |
+
or
|
| 296 |
+
- 2. upon express reinstatement by the Licensor.
|
| 297 |
+
|
| 298 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 299 |
+
right the Licensor may have to seek remedies for Your violations of
|
| 300 |
+
this Public License.
|
| 301 |
+
|
| 302 |
+
- c. For the avoidance of doubt, the Licensor may also offer the
|
| 303 |
+
Licensed Material under separate terms or conditions or stop
|
| 304 |
+
distributing the Licensed Material at any time; however, doing so
|
| 305 |
+
will not terminate this Public License.
|
| 306 |
+
- d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 307 |
+
License.
|
| 308 |
+
|
| 309 |
+
Section 7 – Other Terms and Conditions.
|
| 310 |
+
|
| 311 |
+
- a. The Licensor shall not be bound by any additional or different
|
| 312 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 313 |
+
- b. Any arrangements, understandings, or agreements regarding the
|
| 314 |
+
Licensed Material not stated herein are separate from and
|
| 315 |
+
independent of the terms and conditions of this Public License.
|
| 316 |
+
|
| 317 |
+
Section 8 – Interpretation.
|
| 318 |
+
|
| 319 |
+
- a. For the avoidance of doubt, this Public License does not, and
|
| 320 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 321 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 322 |
+
be made without permission under this Public License.
|
| 323 |
+
- b. To the extent possible, if any provision of this Public License
|
| 324 |
+
is deemed unenforceable, it shall be automatically reformed to the
|
| 325 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 326 |
+
cannot be reformed, it shall be severed from this Public License
|
| 327 |
+
without affecting the enforceability of the remaining terms and
|
| 328 |
+
conditions.
|
| 329 |
+
- c. No term or condition of this Public License will be waived and no
|
| 330 |
+
failure to comply consented to unless expressly agreed to by the
|
| 331 |
+
Licensor.
|
| 332 |
+
- d. Nothing in this Public License constitutes or may be interpreted
|
| 333 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 334 |
+
that apply to the Licensor or You, including from the legal
|
| 335 |
+
processes of any jurisdiction or authority.
|
| 336 |
+
|
| 337 |
+
Creative Commons is not a party to its public licenses. Notwithstanding,
|
| 338 |
+
Creative Commons may elect to apply one of its public licenses to
|
| 339 |
+
material it publishes and in those instances will be considered the
|
| 340 |
+
"Licensor." The text of the Creative Commons public licenses is
|
| 341 |
+
dedicated to the public domain under the CC0 Public Domain Dedication.
|
| 342 |
+
Except for the limited purpose of indicating that material is shared
|
| 343 |
+
under a Creative Commons public license or as otherwise permitted by the
|
| 344 |
+
Creative Commons policies published at creativecommons.org/policies,
|
| 345 |
+
Creative Commons does not authorize the use of the trademark "Creative
|
| 346 |
+
Commons" or any other trademark or logo of Creative Commons without its
|
| 347 |
+
prior written consent including, without limitation, in connection with
|
| 348 |
+
any unauthorized modifications to any of its public licenses or any
|
| 349 |
+
other arrangements, understandings, or agreements concerning use of
|
| 350 |
+
licensed material. For the avoidance of doubt, this paragraph does not
|
| 351 |
+
form part of the public licenses.
|
| 352 |
+
|
| 353 |
+
Creative Commons may be contacted at creativecommons.org.
|
README.md
CHANGED
|
@@ -1,153 +1,244 @@
|
|
| 1 |
-
---
|
| 2 |
-
library_name: transformers
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
-
|
| 6 |
-
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
```python
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
``
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
```
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
license: "cc-by-nc-sa-4.0"
|
| 4 |
+
tags:
|
| 5 |
+
- protein-language-model
|
| 6 |
+
- fastplms
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
<!-- Generated from src/fastplms/models.toml. Do not edit. -->
|
| 10 |
+
|
| 11 |
+
# Synthyra/ANKH2_large
|
| 12 |
+
|
| 13 |
+
This checkpoint packages the FastPLMs `ANKH` implementation.
|
| 14 |
+
|
| 15 |
+
Accepted inputs are amino-acid sequences tokenized for encoder or sequence-to-
|
| 16 |
+
sequence use.
|
| 17 |
+
Supported Transformers entry points are `AutoConfig`, `AutoModel`,
|
| 18 |
+
`AutoModelForMaskedLM`, `AutoModelForSeq2SeqLM`,
|
| 19 |
+
`AutoModelForSequenceClassification`, `AutoModelForTokenClassification`.
|
| 20 |
+
|
| 21 |
+
## Install and platform requirements
|
| 22 |
+
|
| 23 |
+
Install FastPLMs from the exact source revision paired with this model card:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
python -m pip install \
|
| 27 |
+
"fastplms @ git+https://github.com/Synthyra/FastPLMs.git@1b9ce023f1e06571cf3e6324be0610ffa53e0a4a"
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Python 3.11-3.14, PyTorch 2.13, and Transformers 5.13 are required. The declared CPU gate covers tiny offline contracts; published checkpoint throughput and parity require the documented device tier. The Hub quick start below requires network
|
| 31 |
+
access on first download. For an air-gapped run, first build the manifest-pinned
|
| 32 |
+
local artifact and use the offline form shown in the example.
|
| 33 |
+
|
| 34 |
+
## Quick start
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
from transformers import AutoModel
|
| 38 |
+
|
| 39 |
+
model_id = "Synthyra/ANKH2_large"
|
| 40 |
+
model = AutoModel.from_pretrained(
|
| 41 |
+
model_id,
|
| 42 |
+
trust_remote_code=True,
|
| 43 |
+
).eval()
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
This example uses the published Hub repository. For offline validation, build
|
| 47 |
+
the manifest-pinned artifact and replace `model_id` with its local
|
| 48 |
+
`dist/hub/ANKH2_large` path, then pass `local_files_only=True`.
|
| 49 |
+
|
| 50 |
+
Leave attention unspecified for the Transformers default. Supported explicit
|
| 51 |
+
choices are `eager`, `sdpa`.
|
| 52 |
+
Pass the selected name through `attn_implementation`.
|
| 53 |
+
When an optimized backend cannot return full attention tensors,
|
| 54 |
+
`output_attentions=True` emits one explicit runtime warning and uses a correctly
|
| 55 |
+
masked eager implementation for that call only. The warning identifies the
|
| 56 |
+
configured backend, effective backend, and reason. Configuration and later
|
| 57 |
+
calls are unchanged.
|
| 58 |
+
For BF16 execution, this family uses parameters loaded directly in BF16.
|
| 59 |
+
|
| 60 |
+
## Tokenization and forward inference
|
| 61 |
+
|
| 62 |
+
The live `Synthyra/ANKH2_large` revision `392de5ed52bbfd73b45f545e378aaebcff096d0e` is legacy
|
| 63 |
+
encoder-only. The Hub quick start above is therefore an encoder-only
|
| 64 |
+
`AutoModel` path, not evidence that decoder or language-model-head weights are
|
| 65 |
+
already published.
|
| 66 |
+
|
| 67 |
+
Use the tokenizer owned by the loaded model so tokenizer files, revision,
|
| 68 |
+
offline/cache policy, and ANKH's residue-aware pre-tokenizer stay aligned.
|
| 69 |
+
Pass raw protein strings without inserted residue spaces:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
import torch
|
| 73 |
+
|
| 74 |
+
tokenizer = model.tokenizer
|
| 75 |
+
batch = tokenizer(
|
| 76 |
+
["MSTNPKPQRKTKRNT", "MKTIIALSYIFCLVFA"],
|
| 77 |
+
padding=True,
|
| 78 |
+
return_tensors="pt",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
with torch.inference_mode():
|
| 82 |
+
output = model(**batch)
|
| 83 |
+
|
| 84 |
+
print(output.last_hidden_state.shape)
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## Dataset embeddings
|
| 88 |
+
|
| 89 |
+
The current live Hub revision is legacy encoder-only. It supports encoder
|
| 90 |
+
dataset embeddings, which default to the encoder's final hidden state. Layer
|
| 91 |
+
indices use the selected stack's native hidden-state order:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
encoder_result = model.embed_dataset(
|
| 95 |
+
["MSTNPKPQRKTKRNT"],
|
| 96 |
+
hidden_state_source="encoder",
|
| 97 |
+
hidden_state_index=-1,
|
| 98 |
+
full_embeddings=True,
|
| 99 |
+
)
|
| 100 |
+
all_encoder_layers = model.embed_dataset(
|
| 101 |
+
["MSTNPKPQRKTKRNT"],
|
| 102 |
+
hidden_state_source="encoder",
|
| 103 |
+
store_all_hidden_states=True,
|
| 104 |
+
full_embeddings=True,
|
| 105 |
+
)
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
Decoder representations require `AutoModelForSeq2SeqLM` and exactly one
|
| 109 |
+
explicit, aligned `decoder_inputs` sequence or `decoder_input_ids` tensor. ANKH
|
| 110 |
+
does not infer a shifted source sequence because official tasks use prompts,
|
| 111 |
+
sentinel tokens, or generated tokens that depend on the task. Protein inputs
|
| 112 |
+
remain raw residue strings and sentinel prompts remain tight, as in
|
| 113 |
+
`M<extra_id_0>`. Until the atomic Hub replacement is published, load the
|
| 114 |
+
validated complete local artifact and fail closed on its registry-bound
|
| 115 |
+
attestation:
|
| 116 |
+
|
| 117 |
+
```python
|
| 118 |
+
from pathlib import Path
|
| 119 |
+
from transformers import AutoModelForSeq2SeqLM
|
| 120 |
+
from fastplms.registry import get_model_registry
|
| 121 |
+
from tools.artifacts.build import validate_artifact
|
| 122 |
+
|
| 123 |
+
artifact = Path("dist/hub/ANKH2_large").resolve()
|
| 124 |
+
registry = get_model_registry()
|
| 125 |
+
validate_artifact(artifact, spec=registry["ankh2_large"], registry=registry)
|
| 126 |
+
seq2seq = AutoModelForSeq2SeqLM.from_pretrained(
|
| 127 |
+
artifact,
|
| 128 |
+
trust_remote_code=True,
|
| 129 |
+
local_files_only=True,
|
| 130 |
+
).eval()
|
| 131 |
+
decoder_result = seq2seq.embed_dataset(
|
| 132 |
+
["MSTNPKPQRKTKRNT"],
|
| 133 |
+
hidden_state_source="decoder",
|
| 134 |
+
hidden_state_index=-1,
|
| 135 |
+
decoder_inputs=["M<extra_id_0>"],
|
| 136 |
+
full_embeddings=True,
|
| 137 |
+
)
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
`decoder_attention_mask` is accepted only with `decoder_input_ids`. Decoder
|
| 141 |
+
pooling excludes start, EOS, padding, sentinel, and other tokenizer-special
|
| 142 |
+
positions. Persisted results record the selected stack and layer, decoder input
|
| 143 |
+
and mask fingerprints, input-position alignment, and biological-mask policy.
|
| 144 |
+
|
| 145 |
+
## Encoder and sequence-to-sequence use
|
| 146 |
+
|
| 147 |
+
The current manifest Hub revision `392de5ed52bbfd73b45f545e378aaebcff096d0e` for
|
| 148 |
+
`Synthyra/ANKH2_large` is legacy encoder-only. It supports the `AutoModel`
|
| 149 |
+
encoder path, but it is not the full FastPLMs 1.0 sequence-to-sequence
|
| 150 |
+
artifact. Do not load `AutoModelForSeq2SeqLM` from that live revision.
|
| 151 |
+
|
| 152 |
+
The full encoder-decoder replacement is still pending atomic publication. Use
|
| 153 |
+
sequence-to-sequence behavior only from a locally built artifact whose complete
|
| 154 |
+
weight, runtime, provenance, and registry validation has passed. The following
|
| 155 |
+
snippet fails closed if that artifact is missing or invalid:
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
import torch
|
| 159 |
+
from pathlib import Path
|
| 160 |
+
from transformers import AutoModelForSeq2SeqLM
|
| 161 |
+
from fastplms.registry import get_model_registry
|
| 162 |
+
from tools.artifacts.build import validate_artifact
|
| 163 |
+
|
| 164 |
+
artifact = Path("dist/hub/ANKH2_large").resolve()
|
| 165 |
+
registry = get_model_registry()
|
| 166 |
+
validate_artifact(artifact, spec=registry["ankh2_large"], registry=registry)
|
| 167 |
+
seq2seq = AutoModelForSeq2SeqLM.from_pretrained(
|
| 168 |
+
artifact,
|
| 169 |
+
trust_remote_code=True,
|
| 170 |
+
local_files_only=True,
|
| 171 |
+
).eval()
|
| 172 |
+
tokenizer = seq2seq.tokenizer
|
| 173 |
+
batch = tokenizer("MSTNPKPQRKTKRNT", return_tensors="pt")
|
| 174 |
+
|
| 175 |
+
with torch.inference_mode():
|
| 176 |
+
generated_ids = seq2seq.generate(**batch, max_new_tokens=16)
|
| 177 |
+
print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True))
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
ANKH artifacts retain CC BY-NC-SA 4.0 terms. The notes below distinguish the
|
| 181 |
+
official heads from FastPLMs extensions. Once validated and published, the 1.0
|
| 182 |
+
replacement will increase the default repository size while preserving
|
| 183 |
+
encoder-output parity. Runtime code,
|
| 184 |
+
configuration, tokenizer, card, provenance, and every weight shard must be
|
| 185 |
+
published atomically. Files-only publication is forbidden for this migration.
|
| 186 |
+
|
| 187 |
+
## Notes and limitations
|
| 188 |
+
|
| 189 |
+
ANKH parity covers the official encoder and sequence-to-sequence heads.
|
| 190 |
+
AutoModelForMaskedLM exposes the separately named FastPLMs synthesized
|
| 191 |
+
masked-LM extension and is not an official ANKH head.
|
| 192 |
+
|
| 193 |
+
## Runtime contract
|
| 194 |
+
|
| 195 |
+
- Public input: Amino-acid sequences tokenized for encoder or sequence-to-sequence use
|
| 196 |
+
- Advertised AutoClasses: `AutoConfig`, `AutoModel`, `AutoModelForMaskedLM`, `AutoModelForSeq2SeqLM`, `AutoModelForSequenceClassification`, `AutoModelForTokenClassification`
|
| 197 |
+
- AutoClass weight status: `AutoConfig` = `FastPLMs extension`, `AutoModel` = `pretrained`, `AutoModelForMaskedLM` = `FastPLMs extension`, `AutoModelForSeq2SeqLM` = `pretrained`, `AutoModelForSequenceClassification` = `base weights + untrained task head`, `AutoModelForTokenClassification` = `base weights + untrained task head`
|
| 198 |
+
- Attention implementations: `eager`, `sdpa`
|
| 199 |
+
- Precision policies: `default`
|
| 200 |
+
- BF16 execution: `static_parameters`
|
| 201 |
+
- Generation contract: `required`
|
| 202 |
+
- Optional dependency group: `core`
|
| 203 |
+
- Weight publication allowed: `true`
|
| 204 |
+
- Weight license status: `resolved`
|
| 205 |
+
- Redistributable: `true`
|
| 206 |
+
- Complete weight publication required: `true`
|
| 207 |
+
|
| 208 |
+
## Provenance
|
| 209 |
+
|
| 210 |
+
- FastPLMs weights: `Synthyra/ANKH2_large@392de5ed52bbfd73b45f545e378aaebcff096d0e`
|
| 211 |
+
- Runtime revision: `1b9ce023f1e06571cf3e6324be0610ffa53e0a4a`
|
| 212 |
+
- Runtime source-tree SHA-256: `5eb598fd991b5447e3bb6a18c92bd2300be1d94a1e169504725bc56127c1d6bc`
|
| 213 |
+
- Runtime bundle SHA-256: `17b8f83a33e63d941e3edfb8db2d8381286046b572f94194e576ca394d997597`
|
| 214 |
+
- Generator/schema version and complete/runtime-only attestations: recorded in `provenance.json`
|
| 215 |
+
- Canonical transformed state SHA-256: `597c4fe2fa8711f11a25317905f1d62fa92905e55fdd5c0a79614cd9c9d2bca3`
|
| 216 |
+
- Conversion equality attestation: recorded in `provenance.json`
|
| 217 |
+
- Official checkpoint: `ElnaggarLab/ankh2-ext2@aa9b9fa72288c47d9f618ce80c011e24b54e17a8`
|
| 218 |
+
- Artifact source: `official`
|
| 219 |
+
- State transform: `ankh_t5_to_fastplms_v1`
|
| 220 |
+
- BF16 execution: `static_parameters`
|
| 221 |
+
- Pinned upstreams: `ankh`
|
| 222 |
+
- Reference container: `reference-ankh`
|
| 223 |
+
- Release tiers: `check`, `compliance`, `feature`, `artifact`, `benchmark`
|
| 224 |
+
- Unresolved required file identities: `0`
|
| 225 |
+
|
| 226 |
+
The local artifact records exact file identities, conversion provenance, source
|
| 227 |
+
revisions, and legal texts in `provenance.json`. A nonzero unresolved count is a
|
| 228 |
+
release blocker.
|
| 229 |
+
|
| 230 |
+
## Validation boundary
|
| 231 |
+
|
| 232 |
+
For tiers declared by the manifest, the release contract compares applicable
|
| 233 |
+
semantic configuration, tokenizer behavior, state keys, shapes, dtypes,
|
| 234 |
+
values, aliases, and representative inference with the pinned official
|
| 235 |
+
implementation. This metadata does not by itself claim that a particular build
|
| 236 |
+
passed, that one backend is faster, or that an output has biological or
|
| 237 |
+
therapeutic validity.
|
| 238 |
+
|
| 239 |
+
## License
|
| 240 |
+
|
| 241 |
+
Checkpoint terms: CC-BY-NC-SA-4.0. The Hub model-card identifier is
|
| 242 |
+
`cc-by-nc-sa-4.0`. Applicable source licenses, notices, attribution,
|
| 243 |
+
and conversion records are distributed with the local artifact. Review them
|
| 244 |
+
before use.
|
THIRD_PARTY_NOTICES.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party notices
|
| 2 |
+
|
| 3 |
+
FastPLMs implements interfaces and checkpoint mappings for independently
|
| 4 |
+
released protein models. The pinned repositories under `vendor/upstream/` are
|
| 5 |
+
parity oracles. Production code does not import them, and runtime images do not
|
| 6 |
+
contain them.
|
| 7 |
+
|
| 8 |
+
This notice is informational and is not legal advice. A checkpoint license can
|
| 9 |
+
differ from the license covering its source implementation. The typed inventory
|
| 10 |
+
in `src/fastplms/models.toml` and the verbatim files under `LICENSES/` are the
|
| 11 |
+
distribution record.
|
| 12 |
+
|
| 13 |
+
## ANKH
|
| 14 |
+
|
| 15 |
+
The pinned ANKH implementation and the mirrored ANKH checkpoints are identified
|
| 16 |
+
as CC BY-NC-SA 4.0. FastPLMs displays those terms but does not enforce them in
|
| 17 |
+
software. Users are responsible for determining whether their use and
|
| 18 |
+
redistribution comply. The complete text is in `LICENSES/ankh/LICENSE.md`.
|
| 19 |
+
|
| 20 |
+
## Profluent-E1
|
| 21 |
+
|
| 22 |
+
Profluent identifies its E1 model code as Apache-2.0. The E1 weights and full
|
| 23 |
+
release are subject to the Profluent-E1 Clickthrough License Agreement and the
|
| 24 |
+
incorporated attribution requirements. Any E1 distribution must retain all of
|
| 25 |
+
the following files:
|
| 26 |
+
|
| 27 |
+
- `LICENSES/e1/LICENSE`, the Profluent-E1 agreement
|
| 28 |
+
- `LICENSES/e1/ATTRIBUTION`, the attribution guidelines
|
| 29 |
+
- `LICENSES/e1/NOTICE`, the required notice
|
| 30 |
+
- `LICENSES/e1/Apache-2.0.txt`, the code license
|
| 31 |
+
- `LICENSES/e1/BSD-3-Clause.txt`, covering the FlashAttention-derived padding
|
| 32 |
+
utility identified by the official E1 source
|
| 33 |
+
- `LICENSES/e1/MODIFICATIONS.md`, the FastPLMs modified-file notice
|
| 34 |
+
|
| 35 |
+
The exact text `Profluent-E1` must remain prominently displayed in E1
|
| 36 |
+
documentation and at each launch of an executable E1 workflow, as required by
|
| 37 |
+
the upstream attribution guidelines. Certain commercial outputs, including
|
| 38 |
+
specified pharmaceutical and target-related outputs, can require the separate
|
| 39 |
+
`Built with Profluent-E1` statement described in `ATTRIBUTION`.
|
| 40 |
+
|
| 41 |
+
## DPLM
|
| 42 |
+
|
| 43 |
+
The pinned ByteDance DPLM repository is Apache-2.0. Its
|
| 44 |
+
[README](https://github.com/bytedance/dplm/blob/8a2e15e53416b4536f03f79ad1f6f6a9cbd5e19d/README.md#overview)
|
| 45 |
+
explicitly defines the repository release as including pretrained DPLM1 and
|
| 46 |
+
DPLM2 weights, and the same revision carries the complete
|
| 47 |
+
[Apache-2.0 license](https://github.com/bytedance/dplm/blob/8a2e15e53416b4536f03f79ad1f6f6a9cbd5e19d/LICENSE).
|
| 48 |
+
FastPLMs records both checkpoint families as Apache-2.0 and distributes the
|
| 49 |
+
verbatim license plus `LICENSES/dplm/PROVENANCE.md`. Converted weights retain
|
| 50 |
+
those terms and remain subject to the ordinary artifact and publication gates.
|
| 51 |
+
|
| 52 |
+
## Biohub
|
| 53 |
+
|
| 54 |
+
The pinned Biohub ESM implementation is MIT and includes a separate
|
| 55 |
+
`THIRD_PARTY_NOTICE.md`; both files are distributed under
|
| 56 |
+
`LICENSES/biohub-esm/`. The pinned Biohub Transformers fork is Apache-2.0, with
|
| 57 |
+
its complete text under `LICENSES/biohub-transformers/`.
|
| 58 |
+
|
| 59 |
+
## Boltz
|
| 60 |
+
|
| 61 |
+
The pinned Boltz source is MIT. The verbatim notice is in
|
| 62 |
+
`LICENSES/boltz/LICENSE`.
|
| 63 |
+
|
| 64 |
+
## Meta ESM and OpenFold
|
| 65 |
+
|
| 66 |
+
The pinned Meta ESM source is MIT. The pinned OpenFold source is Apache-2.0.
|
| 67 |
+
Their verbatim texts and revision-specific provenance notices are under
|
| 68 |
+
`LICENSES/fair-esm/` and `LICENSES/openfold/`.
|
| 69 |
+
|
| 70 |
+
The native H100 ESMFold reference image applies the tracked
|
| 71 |
+
`docker/constraints/openfold-sm90.patch` to the copied OpenFold `setup.py`.
|
| 72 |
+
This build-only change restricts the CUDA extension to `sm90` and selects the
|
| 73 |
+
C++17 standard required by the reference PyTorch version. It leaves the pinned
|
| 74 |
+
submodule, extension source, model classes, checkpoint data, and public API
|
| 75 |
+
unchanged. The complete modified-file record is in
|
| 76 |
+
`LICENSES/openfold/MODIFICATIONS.md`.
|
| 77 |
+
|
| 78 |
+
The isolated reference image also includes Apache-2.0 PyTorch Lightning,
|
| 79 |
+
TorchMetrics, Lightning Utilities, and NVIDIA DLLogger. Their exact versions or
|
| 80 |
+
revision are pinned in `docker/constraints/esmfold.txt`; OpenFold imports them
|
| 81 |
+
eagerly, and FastPLMs production code does not depend on them. DLLogger's exact
|
| 82 |
+
source identity and installed-license handling are recorded in
|
| 83 |
+
`LICENSES/dllogger/PROVENANCE.md`.
|
| 84 |
+
|
| 85 |
+
## ProteinTTT
|
| 86 |
+
|
| 87 |
+
The optional test-time training workflow is validated against the pinned
|
| 88 |
+
ProteinTTT repository under its MIT license. Its verbatim license and
|
| 89 |
+
revision-specific provenance are under `LICENSES/protein-ttt/`.
|
| 90 |
+
|
| 91 |
+
## Conversion and packaging record
|
| 92 |
+
|
| 93 |
+
For every supported family, `src/fastplms/models.toml` records an immutable
|
| 94 |
+
official checkpoint revision, an immutable FastPLMs checkpoint revision, file
|
| 95 |
+
digests, a named state transformation, and a mechanism-level conversion record.
|
| 96 |
+
Generated artifacts reproduce that record in `provenance.json`. A release or
|
| 97 |
+
artifact build must fail when a required file identity, legal text, attribution
|
| 98 |
+
notice, modified-file notice, upstream revision, or conversion record is absent
|
| 99 |
+
or differs from its manifest digest.
|
artifact-manifest.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"LICENSES/FastPLMs-Apache-2.0.txt": "sha256:2d2b50c7b1414bff1189a1db1f0cfb92e3e064b50f4c2b1019827b683e1b629a",
|
| 3 |
+
"LICENSES/ankh/LICENSE.md": "sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088",
|
| 4 |
+
"README.md": "sha256:d34607e87e0df11a9d8cea1e8dd541d1fe79761f90cfc2d95c9cb5135e0ccbbc",
|
| 5 |
+
"THIRD_PARTY_NOTICES.md": "sha256:25704b3c76404696cae52e7fca13088d329f70f412687340351259e86cd62baa",
|
| 6 |
+
"config.json": "sha256:fe9df500b8e73df29eff467f41a92d9bf1489ba7ac8c151f237f700f41b1b7a1",
|
| 7 |
+
"fastplms/__init__.py": "sha256:4fb3196022ca8ec699d59d09bdbc5f0184195552b773698ab9b061fe3cd7df12",
|
| 8 |
+
"fastplms/attention/__init__.py": "sha256:f60b9fecfb4bcb37a4e7c26dc2f752b9035f9cbad627b4a84213f3a92ec88f7d",
|
| 9 |
+
"fastplms/attention/_core.py": "sha256:8f7ec5b65bd8b6c6fa4951d50d1c0e499abf03ae00914794b51fc410201e3e33",
|
| 10 |
+
"fastplms/attention/_kernel_lock.py": "sha256:85d8521a2af5f94fad3948af3814db0c866c414ee4d43df797b9bd6f980e947b",
|
| 11 |
+
"fastplms/attention/interfaces.py": "sha256:1c6f06a8e411e0f9bf6d230522205c93ae46ea58864006fbb892aa05e5ca5749",
|
| 12 |
+
"fastplms/embeddings/__init__.py": "sha256:47ff8cdf682d44037dd9edab133e2e60675d60786bd5cf0bffd1998f31985555",
|
| 13 |
+
"fastplms/embeddings/pooling.py": "sha256:a140266ed6b1cc344c8507edc5c6c4f2dce464c3db70ba4b16c7ac2ba2fad96e",
|
| 14 |
+
"fastplms/embeddings/runner.py": "sha256:23ee4727a918d6d331f7a0f89b823d149f1a791f0c5586e3496d7b6eb2ce97e0",
|
| 15 |
+
"fastplms/embeddings/storage.py": "sha256:3fbe2bab75092e5a4cadf4d27e4752181d597469a65a55db085ceef808ed418e",
|
| 16 |
+
"fastplms/embeddings/types.py": "sha256:119718a20989d1ae5a60fabc0f5e98bdc172c5163b04db3d4554ac3956b30e52",
|
| 17 |
+
"fastplms/models.toml": "sha256:05a8399f084a5babb5f0916cee7e564c4030767f3ff0230c4f46e539209847d1",
|
| 18 |
+
"fastplms/models/__init__.py": "sha256:5e48c2cb3877aa6f42f3b5411d53b16bba2e32827bbde634f47f174c5cb36f86",
|
| 19 |
+
"fastplms/models/ankh/__init__.py": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 20 |
+
"fastplms/models/ankh/modeling_ankh.py": "sha256:b114c73e4aaedc567e3351b425ddddacf35661f09b3414cf59b6db0b712c82c3",
|
| 21 |
+
"fastplms/models/ttt.py": "sha256:a0df4e98b02120d423e3c7ca9b866a8d0e3748b9076042a0102a838a11aed046",
|
| 22 |
+
"fastplms/registry.py": "sha256:afca271911b651a882345b74a58366494a1d784e4a48c8683a87f5508f4ba16e",
|
| 23 |
+
"fastplms/runtime.py": "sha256:110018646d6f248cedab140a030c3065e1b062b61f6aff659c231e538614bc01",
|
| 24 |
+
"fastplms_bundle.py": "sha256:ebf70cf52fb0a07025edf06bd50d2e945d9ed09fe12e6d3ae3503001ec21c9f9",
|
| 25 |
+
"generation_config.json": "sha256:53e38d7cba6a16e598cd75a7acae25573674dc0ecdbf290ed19b46e0b4dd8c75",
|
| 26 |
+
"model-00001-of-00002.safetensors": "sha256:7c0c297f60bcf81c732cdfeae6e99e140272807eb52afd70356fc6fdfa94e5a8",
|
| 27 |
+
"model-00002-of-00002.safetensors": "sha256:f3d425d3e8741ccbdd925446559a9bf317c2c91e328f2eee44924423b56e3a3d",
|
| 28 |
+
"model.safetensors.index.json": "sha256:eb9f1a3b03bd5fc5dd912aa4244181ed09e19b99a57c2e1d95bdf952e510cea3",
|
| 29 |
+
"modeling_fastplms.py": "sha256:df7f6d96802eff127bc8270cde5fe00c8f5e77921c1cc893021fb9f75a3e4c77",
|
| 30 |
+
"provenance.json": "sha256:47a519cbd68eefcd5baac2bd4e2331be145e861d3b549e0ac41b83500f2c9bbe",
|
| 31 |
+
"runtime-attestation.json": "sha256:92db6caed50673b1bf451b43847d01e356e6e87ba6fc17e7ddd315faded2cb97",
|
| 32 |
+
"special_tokens_map.json": "sha256:c8995d2f8037fe3a8cfdef30475365e1c314c417880b75abaf8296e3c05d42d6",
|
| 33 |
+
"tokenizer.json": "sha256:b4533f607d9fd665f2d9d94b0cf71870a6fc2fc2ae7cbd516d0e43a9efb406fd",
|
| 34 |
+
"tokenizer_config.json": "sha256:dba1f9315ded007fc2e5bcb2ed4bfb6fff81c9becdc97b73a5713ba5ddc01afc"
|
| 35 |
+
}
|
config.json
CHANGED
|
@@ -1,26 +1,49 @@
|
|
| 1 |
{
|
| 2 |
-
"
|
|
|
|
|
|
|
|
|
|
| 3 |
"auto_map": {
|
| 4 |
-
"AutoConfig": "
|
| 5 |
-
"AutoModel": "
|
| 6 |
-
"AutoModelForMaskedLM": "
|
| 7 |
-
"
|
| 8 |
-
"
|
|
|
|
| 9 |
},
|
| 10 |
"d_ff": 3840,
|
| 11 |
"d_kv": 64,
|
| 12 |
"d_model": 1536,
|
|
|
|
| 13 |
"dense_act_fn": "silu",
|
|
|
|
| 14 |
"eos_token_id": 1,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"initializer_factor": 1.0,
|
|
|
|
|
|
|
| 16 |
"layer_norm_epsilon": 1e-06,
|
| 17 |
-
"model_type": "
|
|
|
|
| 18 |
"num_heads": 16,
|
| 19 |
"num_layers": 48,
|
|
|
|
| 20 |
"pad_token_id": 0,
|
| 21 |
"relative_attention_max_distance": 128,
|
| 22 |
"relative_attention_num_buckets": 64,
|
| 23 |
"tie_word_embeddings": false,
|
| 24 |
-
"
|
|
|
|
|
|
|
| 25 |
"vocab_size": 144
|
| 26 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"_name_or_path": "agemagician/protx-large-1gspan-partreconst-15mlmp-encl48-decl24-ramd128-ranb64-dmodel1536-silu-seq768-tpuv4",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"T5ForConditionalGeneration"
|
| 5 |
+
],
|
| 6 |
"auto_map": {
|
| 7 |
+
"AutoConfig": "modeling_fastplms.FastAnkhConfig",
|
| 8 |
+
"AutoModel": "modeling_fastplms.FastAnkhModel",
|
| 9 |
+
"AutoModelForMaskedLM": "modeling_fastplms.FastAnkhForMaskedLMExtension",
|
| 10 |
+
"AutoModelForSeq2SeqLM": "modeling_fastplms.FastAnkhForConditionalGeneration",
|
| 11 |
+
"AutoModelForSequenceClassification": "modeling_fastplms.FastAnkhForSequenceClassification",
|
| 12 |
+
"AutoModelForTokenClassification": "modeling_fastplms.FastAnkhForTokenClassification"
|
| 13 |
},
|
| 14 |
"d_ff": 3840,
|
| 15 |
"d_kv": 64,
|
| 16 |
"d_model": 1536,
|
| 17 |
+
"decoder_start_token_id": 0,
|
| 18 |
"dense_act_fn": "silu",
|
| 19 |
+
"dropout_rate": 0.0,
|
| 20 |
"eos_token_id": 1,
|
| 21 |
+
"fastplms_checkpoint_hash": "ca31eec9942e836d0b557a94d3b50e642af3738627a348d6526a6968b8646f8c",
|
| 22 |
+
"fastplms_checkpoint_repo_id": "ElnaggarLab/ankh2-ext2",
|
| 23 |
+
"fastplms_checkpoint_revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8",
|
| 24 |
+
"fastplms_model_id": "ankh2_large",
|
| 25 |
+
"fastplms_release_tool_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 26 |
+
"fastplms_release_tool_sha256": "1459b5d7d13d9b07bd97b3eee764f2ce73623e15e32d07ddf6825c2a9509afb9",
|
| 27 |
+
"fastplms_runtime_bundle_sha256": "17b8f83a33e63d941e3edfb8db2d8381286046b572f94194e576ca394d997597",
|
| 28 |
+
"fastplms_runtime_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 29 |
+
"fastplms_source_tree_sha256": "5eb598fd991b5447e3bb6a18c92bd2300be1d94a1e169504725bc56127c1d6bc",
|
| 30 |
+
"fastplms_weights_revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8",
|
| 31 |
+
"feed_forward_proj": "gated-silu",
|
| 32 |
"initializer_factor": 1.0,
|
| 33 |
+
"is_encoder_decoder": true,
|
| 34 |
+
"is_gated_act": true,
|
| 35 |
"layer_norm_epsilon": 1e-06,
|
| 36 |
+
"model_type": "t5",
|
| 37 |
+
"num_decoder_layers": 24,
|
| 38 |
"num_heads": 16,
|
| 39 |
"num_layers": 48,
|
| 40 |
+
"output_past": true,
|
| 41 |
"pad_token_id": 0,
|
| 42 |
"relative_attention_max_distance": 128,
|
| 43 |
"relative_attention_num_buckets": 64,
|
| 44 |
"tie_word_embeddings": false,
|
| 45 |
+
"torch_dtype": "float32",
|
| 46 |
+
"transformers_version": "4.26.1",
|
| 47 |
+
"use_cache": true,
|
| 48 |
"vocab_size": 144
|
| 49 |
}
|
fastplms/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastPLMs public package interface.
|
| 2 |
+
|
| 3 |
+
The module uses lazy exports so importing :mod:`fastplms` does not initialize
|
| 4 |
+
Torch, download checkpoints, construct tokenizers, or compile kernels.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from importlib import import_module
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
__version__ = "1.0.0"
|
| 13 |
+
|
| 14 |
+
_LAZY_EXPORTS = {
|
| 15 |
+
"CheckpointSource": ("fastplms.registry", "CheckpointSource"),
|
| 16 |
+
"EmbeddingInput": ("fastplms.embeddings", "EmbeddingInput"),
|
| 17 |
+
"EmbeddingRecord": ("fastplms.embeddings", "EmbeddingRecord"),
|
| 18 |
+
"EmbeddingResult": ("fastplms.embeddings", "EmbeddingResult"),
|
| 19 |
+
"FileDigest": ("fastplms.registry", "FileDigest"),
|
| 20 |
+
"ModelFamily": ("fastplms.registry", "ModelFamily"),
|
| 21 |
+
"ModelRegistry": ("fastplms.registry", "ModelRegistry"),
|
| 22 |
+
"ModelSpec": ("fastplms.registry", "ModelSpec"),
|
| 23 |
+
"OracleAsset": ("fastplms.registry", "OracleAsset"),
|
| 24 |
+
"RegistryError": ("fastplms.registry", "RegistryError"),
|
| 25 |
+
"RuntimeProfile": ("fastplms.runtime", "RuntimeProfile"),
|
| 26 |
+
"UpstreamSource": ("fastplms.registry", "UpstreamSource"),
|
| 27 |
+
"embed_dataset": ("fastplms.embeddings", "embed_dataset"),
|
| 28 |
+
"get_model_registry": ("fastplms.registry", "get_model_registry"),
|
| 29 |
+
"get_model_spec": ("fastplms.registry", "get_model_spec"),
|
| 30 |
+
"load_model_registry": ("fastplms.registry", "load_model_registry"),
|
| 31 |
+
"runtime_profile": ("fastplms.runtime", "runtime_profile"),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
__all__ = ["__version__", *_LAZY_EXPORTS]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def __getattr__(name: str) -> Any:
|
| 38 |
+
try:
|
| 39 |
+
module_name, attribute_name = _LAZY_EXPORTS[name]
|
| 40 |
+
except KeyError as error:
|
| 41 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from error
|
| 42 |
+
value = getattr(import_module(module_name), attribute_name)
|
| 43 |
+
globals()[name] = value
|
| 44 |
+
return value
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def __dir__() -> list[str]:
|
| 48 |
+
return sorted(set(globals()).union(__all__))
|
fastplms/attention/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared attention backends, masks, and optional optimized kernels."""
|
| 2 |
+
|
| 3 |
+
from ._core import (
|
| 4 |
+
VALID_ATTENTION_BACKENDS,
|
| 5 |
+
AttentionBackend,
|
| 6 |
+
BlockMask,
|
| 7 |
+
_ensure_flash_kernels_loaded,
|
| 8 |
+
_get_flex_attention_fn,
|
| 9 |
+
_get_flex_block_mask,
|
| 10 |
+
_kernels_flash_forward,
|
| 11 |
+
_kernels_flash_varlen_forward,
|
| 12 |
+
_unpad_input,
|
| 13 |
+
bool_to_additive_mask,
|
| 14 |
+
clear_flex_attention_caches,
|
| 15 |
+
create_block_mask,
|
| 16 |
+
flex_attention,
|
| 17 |
+
get_attention_mask,
|
| 18 |
+
get_attn_implementation,
|
| 19 |
+
index_first_axis,
|
| 20 |
+
index_put_first_axis,
|
| 21 |
+
kernels_flash_attention_func,
|
| 22 |
+
pad_input,
|
| 23 |
+
resolve_attention_backend,
|
| 24 |
+
resolve_attention_backend_for_call,
|
| 25 |
+
set_config_attn_implementation,
|
| 26 |
+
warn_attention_backend_fallback,
|
| 27 |
+
)
|
| 28 |
+
from .interfaces import (
|
| 29 |
+
FASTPLMS_ATTENTION_FUNCTIONS,
|
| 30 |
+
FASTPLMS_ATTENTION_MASKS,
|
| 31 |
+
FastPLMsAttentionMixin,
|
| 32 |
+
validate_transformers_attention_interfaces,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
__all__ = [
|
| 36 |
+
"FASTPLMS_ATTENTION_FUNCTIONS",
|
| 37 |
+
"FASTPLMS_ATTENTION_MASKS",
|
| 38 |
+
"VALID_ATTENTION_BACKENDS",
|
| 39 |
+
"AttentionBackend",
|
| 40 |
+
"BlockMask",
|
| 41 |
+
"FastPLMsAttentionMixin",
|
| 42 |
+
"_ensure_flash_kernels_loaded",
|
| 43 |
+
"_get_flex_attention_fn",
|
| 44 |
+
"_get_flex_block_mask",
|
| 45 |
+
"_kernels_flash_forward",
|
| 46 |
+
"_kernels_flash_varlen_forward",
|
| 47 |
+
"_unpad_input",
|
| 48 |
+
"bool_to_additive_mask",
|
| 49 |
+
"clear_flex_attention_caches",
|
| 50 |
+
"create_block_mask",
|
| 51 |
+
"flex_attention",
|
| 52 |
+
"get_attention_mask",
|
| 53 |
+
"get_attn_implementation",
|
| 54 |
+
"index_first_axis",
|
| 55 |
+
"index_put_first_axis",
|
| 56 |
+
"kernels_flash_attention_func",
|
| 57 |
+
"pad_input",
|
| 58 |
+
"resolve_attention_backend",
|
| 59 |
+
"resolve_attention_backend_for_call",
|
| 60 |
+
"set_config_attn_implementation",
|
| 61 |
+
"validate_transformers_attention_interfaces",
|
| 62 |
+
"warn_attention_backend_fallback",
|
| 63 |
+
]
|
fastplms/attention/_core.py
ADDED
|
@@ -0,0 +1,779 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Low-level attention kernels and mask construction.
|
| 2 |
+
|
| 3 |
+
The public backend contract lives in :mod:`fastplms.attention`. Optional
|
| 4 |
+
kernels are resolved only after a caller explicitly requests them, so importing
|
| 5 |
+
FastPLMs never downloads or compiles code.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import warnings
|
| 11 |
+
from collections import OrderedDict
|
| 12 |
+
from collections.abc import Callable
|
| 13 |
+
from enum import Enum
|
| 14 |
+
from threading import RLock
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from einops import rearrange
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
|
| 20 |
+
from ._kernel_lock import load_locked_kernel
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
|
| 24 |
+
except ImportError:
|
| 25 |
+
create_block_mask = None
|
| 26 |
+
flex_attention = None
|
| 27 |
+
BlockMask = None
|
| 28 |
+
|
| 29 |
+
_MAX_FLEX_CACHE_ENTRIES = 128
|
| 30 |
+
_compiled_flex_attention: OrderedDict[tuple, object] = OrderedDict()
|
| 31 |
+
_flex_block_masks: OrderedDict[tuple, BlockMask] = OrderedDict()
|
| 32 |
+
_flex_cache_lock = RLock()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _remember(cache: OrderedDict, key: tuple, value):
|
| 36 |
+
"""Insert an item into a bounded least-recently-used cache."""
|
| 37 |
+
cache[key] = value
|
| 38 |
+
cache.move_to_end(key)
|
| 39 |
+
while len(cache) > _MAX_FLEX_CACHE_ENTRIES:
|
| 40 |
+
cache.popitem(last=False)
|
| 41 |
+
return value
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def clear_flex_attention_caches() -> None:
|
| 45 |
+
"""Drop FastPLMs-owned compiled Flex callables and block masks.
|
| 46 |
+
|
| 47 |
+
This deliberately does not call :func:`torch.compiler.reset`, which would
|
| 48 |
+
clear process-global Torch compilation state owned by unrelated models.
|
| 49 |
+
Active forwards retain their local references and can complete safely.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
with _flex_cache_lock:
|
| 53 |
+
_compiled_flex_attention.clear()
|
| 54 |
+
_flex_block_masks.clear()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _get_flex_attention_fn(
|
| 58 |
+
*,
|
| 59 |
+
device: torch.device | None = None,
|
| 60 |
+
dtype: torch.dtype | None = None,
|
| 61 |
+
shape: tuple[int, ...] | None = None,
|
| 62 |
+
sequence_lengths: tuple[int, ...] | None = None,
|
| 63 |
+
mask_semantics: str = "padding",
|
| 64 |
+
):
|
| 65 |
+
"""Return a compiled Flex callable for an explicit execution signature.
|
| 66 |
+
|
| 67 |
+
Compilation depends on execution shape, device, dtype, and mask semantics.
|
| 68 |
+
Per-example padding lengths are represented by the ``BlockMask`` argument
|
| 69 |
+
and must not create a new compiled graph for every batch composition.
|
| 70 |
+
"""
|
| 71 |
+
if flex_attention is None:
|
| 72 |
+
return None
|
| 73 |
+
# Retain the keyword for compatibility with remote-code artifacts while
|
| 74 |
+
# deliberately excluding data-dependent lengths from the compile key.
|
| 75 |
+
del sequence_lengths
|
| 76 |
+
flex_mod = torch.nn.attention.flex_attention
|
| 77 |
+
if getattr(flex_mod, "_FLEX_ATTENTION_DISABLE_COMPILE_DEBUG", False):
|
| 78 |
+
return flex_attention
|
| 79 |
+
key = (
|
| 80 |
+
None if device is None else str(device),
|
| 81 |
+
None if dtype is None else str(dtype),
|
| 82 |
+
shape,
|
| 83 |
+
mask_semantics,
|
| 84 |
+
)
|
| 85 |
+
with _flex_cache_lock:
|
| 86 |
+
compiled = _compiled_flex_attention.get(key)
|
| 87 |
+
if compiled is None:
|
| 88 |
+
compiled = torch.compile(flex_attention, dynamic=False)
|
| 89 |
+
_remember(_compiled_flex_attention, key, compiled)
|
| 90 |
+
else:
|
| 91 |
+
_compiled_flex_attention.move_to_end(key)
|
| 92 |
+
return compiled
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _get_flex_block_mask(
|
| 96 |
+
*,
|
| 97 |
+
mask_pattern: torch.Tensor,
|
| 98 |
+
batch_size: int,
|
| 99 |
+
query_length: int,
|
| 100 |
+
key_value_length: int,
|
| 101 |
+
device: torch.device,
|
| 102 |
+
dtype: torch.dtype | None,
|
| 103 |
+
mask_semantics: str,
|
| 104 |
+
mask_mod: Callable[
|
| 105 |
+
[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
|
| 106 |
+
torch.Tensor,
|
| 107 |
+
],
|
| 108 |
+
) -> BlockMask:
|
| 109 |
+
"""Return a bounded, exact-pattern cached Flex ``BlockMask``.
|
| 110 |
+
|
| 111 |
+
The complete pattern is transferred to the host once to avoid a CUDA
|
| 112 |
+
synchronization per batch row. Execution dtype remains part of the key
|
| 113 |
+
because compiled Flex plans can specialize on it even though the pattern
|
| 114 |
+
tensor itself is boolean or integer.
|
| 115 |
+
"""
|
| 116 |
+
if create_block_mask is None:
|
| 117 |
+
raise RuntimeError(
|
| 118 |
+
"'flex_attention' was requested, but torch.create_block_mask is unavailable."
|
| 119 |
+
)
|
| 120 |
+
pattern = mask_pattern.detach().to(device=device).contiguous()
|
| 121 |
+
# One device-to-host transfer is required for an exact cache identity. Use
|
| 122 |
+
# the contiguous buffer directly instead of materializing one Python int
|
| 123 |
+
# per byte, which is prohibitively expensive for long batched sequences.
|
| 124 |
+
host_pattern = pattern.to(device="cpu").contiguous()
|
| 125 |
+
pattern_bytes = host_pattern.view(torch.uint8).numpy().tobytes(order="C")
|
| 126 |
+
cache_key = (
|
| 127 |
+
str(device),
|
| 128 |
+
None if dtype is None else str(dtype),
|
| 129 |
+
(batch_size, query_length, key_value_length),
|
| 130 |
+
str(pattern.dtype),
|
| 131 |
+
pattern_bytes,
|
| 132 |
+
mask_semantics,
|
| 133 |
+
)
|
| 134 |
+
with _flex_cache_lock:
|
| 135 |
+
flex_block_mask = _flex_block_masks.get(cache_key)
|
| 136 |
+
if flex_block_mask is None:
|
| 137 |
+
flex_block_mask = create_block_mask(
|
| 138 |
+
mask_mod,
|
| 139 |
+
batch_size,
|
| 140 |
+
1,
|
| 141 |
+
query_length,
|
| 142 |
+
key_value_length,
|
| 143 |
+
device=device,
|
| 144 |
+
)
|
| 145 |
+
_remember(_flex_block_masks, cache_key, flex_block_mask)
|
| 146 |
+
else:
|
| 147 |
+
_flex_block_masks.move_to_end(cache_key)
|
| 148 |
+
return flex_block_mask
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# Hugging Face `kernels` exposes slightly different APIs for FlashAttention 2
|
| 152 |
+
# and 3. Detect the loaded variant once so every caller uses the same dispatch.
|
| 153 |
+
def _infer_kernels_flash_variant(kernel) -> str | None:
|
| 154 |
+
if hasattr(kernel, "fwd") and hasattr(kernel, "varlen_fwd"):
|
| 155 |
+
return "flash_attn2"
|
| 156 |
+
if hasattr(kernel, "flash_attn_func") and hasattr(kernel, "flash_attn_varlen_func"):
|
| 157 |
+
return "flash_attn3"
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _load_kernels_flash(implementation: str) -> tuple[object, str]:
|
| 162 |
+
"""Load exactly the requested FlashAttention kernel.
|
| 163 |
+
|
| 164 |
+
Loading is deferred until backend selection. A FlashAttention-2 request
|
| 165 |
+
never falls through to FlashAttention-3, or vice versa.
|
| 166 |
+
"""
|
| 167 |
+
from fastplms.registry import get_model_registry
|
| 168 |
+
|
| 169 |
+
kernel_spec = get_model_registry().attention_kernels[implementation]
|
| 170 |
+
repository = kernel_spec.repository
|
| 171 |
+
try:
|
| 172 |
+
flash_kernel = load_locked_kernel(repository, kernel_spec.revision)
|
| 173 |
+
except Exception as error:
|
| 174 |
+
raise RuntimeError(
|
| 175 |
+
f"Unable to load the manifest-pinned kernel "
|
| 176 |
+
f"{repository}@{kernel_spec.revision} for {implementation!r}."
|
| 177 |
+
) from error
|
| 178 |
+
flash_kernel_variant = _infer_kernels_flash_variant(flash_kernel)
|
| 179 |
+
if flash_kernel_variant != kernel_spec.expected_variant:
|
| 180 |
+
raise RuntimeError(
|
| 181 |
+
f"{repository}@{kernel_spec.revision} exposed {flash_kernel_variant!r}; "
|
| 182 |
+
f"expected {kernel_spec.expected_variant!r}."
|
| 183 |
+
)
|
| 184 |
+
if not all(
|
| 185 |
+
callable(getattr(flash_kernel, name, None))
|
| 186 |
+
for name in ("flash_attn_func", "flash_attn_varlen_func")
|
| 187 |
+
):
|
| 188 |
+
raise RuntimeError(
|
| 189 |
+
f"{repository}@{kernel_spec.revision} does not expose the "
|
| 190 |
+
"autograd-enabled flash_attn_func and flash_attn_varlen_func APIs."
|
| 191 |
+
)
|
| 192 |
+
return flash_kernel, flash_kernel_variant
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
_FLASH_KERNELS: dict[str, tuple[object, str]] = {}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _validate_kernels_flash_dtype(
|
| 199 |
+
query_states: torch.Tensor,
|
| 200 |
+
key_states: torch.Tensor,
|
| 201 |
+
value_states: torch.Tensor,
|
| 202 |
+
implementation: str,
|
| 203 |
+
) -> torch.dtype:
|
| 204 |
+
"""Reject dtypes outside the immutable kernel manifest before dispatch."""
|
| 205 |
+
|
| 206 |
+
tensor_dtypes = {query_states.dtype, key_states.dtype, value_states.dtype}
|
| 207 |
+
if len(tensor_dtypes) != 1:
|
| 208 |
+
observed = ", ".join(sorted(str(dtype) for dtype in tensor_dtypes))
|
| 209 |
+
raise RuntimeError(
|
| 210 |
+
f"{implementation!r} requires Q, K, and V to share one dtype; received {observed}."
|
| 211 |
+
)
|
| 212 |
+
runtime_dtype = query_states.dtype
|
| 213 |
+
if (
|
| 214 |
+
runtime_dtype == torch.float32
|
| 215 |
+
and query_states.is_cuda
|
| 216 |
+
and torch.is_autocast_enabled("cuda")
|
| 217 |
+
):
|
| 218 |
+
runtime_dtype = torch.get_autocast_dtype("cuda")
|
| 219 |
+
dtype_names = {
|
| 220 |
+
torch.float32: "float32",
|
| 221 |
+
torch.bfloat16: "bfloat16",
|
| 222 |
+
torch.float16: "float16",
|
| 223 |
+
}
|
| 224 |
+
runtime_dtype_name = dtype_names.get(runtime_dtype, str(runtime_dtype))
|
| 225 |
+
from fastplms.registry import get_model_registry
|
| 226 |
+
|
| 227 |
+
supported = get_model_registry().attention_kernels[implementation].dtypes
|
| 228 |
+
if runtime_dtype_name not in supported:
|
| 229 |
+
expected = ", ".join(supported)
|
| 230 |
+
raise RuntimeError(
|
| 231 |
+
f"{implementation!r} supports only manifest-declared dtype(s) {expected}; "
|
| 232 |
+
f"received {runtime_dtype_name}. Use CUDA BF16 autocast for FP32-resident "
|
| 233 |
+
"models."
|
| 234 |
+
)
|
| 235 |
+
return runtime_dtype
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _validate_kernels_flash_device(
|
| 239 |
+
query_states: torch.Tensor,
|
| 240 |
+
key_states: torch.Tensor,
|
| 241 |
+
value_states: torch.Tensor,
|
| 242 |
+
implementation: str,
|
| 243 |
+
) -> torch.device:
|
| 244 |
+
"""Require Q, K, and V on one CUDA device before loading a kernel."""
|
| 245 |
+
|
| 246 |
+
devices = (query_states.device, key_states.device, value_states.device)
|
| 247 |
+
if len(set(devices)) != 1:
|
| 248 |
+
observed = ", ".join(str(device) for device in devices)
|
| 249 |
+
raise RuntimeError(
|
| 250 |
+
f"{implementation!r} requires Q, K, and V on one device; received {observed}."
|
| 251 |
+
)
|
| 252 |
+
device = devices[0]
|
| 253 |
+
if device.type != "cuda" or not all(
|
| 254 |
+
tensor.is_cuda for tensor in (query_states, key_states, value_states)
|
| 255 |
+
):
|
| 256 |
+
raise RuntimeError(
|
| 257 |
+
f"{implementation!r} requires CUDA Q, K, and V; received device {device}."
|
| 258 |
+
)
|
| 259 |
+
return device
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _ensure_flash_kernels_loaded(implementation: str) -> tuple[object, str]:
|
| 263 |
+
cached = _FLASH_KERNELS.get(implementation)
|
| 264 |
+
if cached is not None:
|
| 265 |
+
return cached
|
| 266 |
+
loaded = _load_kernels_flash(implementation)
|
| 267 |
+
_FLASH_KERNELS[implementation] = loaded
|
| 268 |
+
return loaded
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _kernels_flash_forward(
|
| 272 |
+
query_states: torch.Tensor,
|
| 273 |
+
key_states: torch.Tensor,
|
| 274 |
+
value_states: torch.Tensor,
|
| 275 |
+
causal: bool = False,
|
| 276 |
+
softmax_scale: float | None = None,
|
| 277 |
+
implementation: str = "flash_attention_3",
|
| 278 |
+
) -> torch.Tensor:
|
| 279 |
+
"""Flash-attention forward, optionally overriding the softmax scale.
|
| 280 |
+
|
| 281 |
+
When `softmax_scale is None`, the flash kernel applies its default
|
| 282 |
+
`1 / sqrt(head_dim)`. Pass `softmax_scale=1.0` if the caller has already
|
| 283 |
+
pre-scaled Q (the convention used by ESM2, DPLM, DPLM2, E1, ESMFold).
|
| 284 |
+
Failing to override when Q is pre-scaled applies the scale twice and breaks
|
| 285 |
+
parity with eager attention and SDPA.
|
| 286 |
+
"""
|
| 287 |
+
flash_kernel, flash_kernel_variant = _ensure_flash_kernels_loaded(implementation)
|
| 288 |
+
if flash_kernel_variant == "flash_attn2":
|
| 289 |
+
output = flash_kernel.flash_attn_func(
|
| 290 |
+
q=query_states,
|
| 291 |
+
k=key_states,
|
| 292 |
+
v=value_states,
|
| 293 |
+
dropout_p=0.0,
|
| 294 |
+
softmax_scale=softmax_scale,
|
| 295 |
+
causal=causal,
|
| 296 |
+
)
|
| 297 |
+
return output[0] if isinstance(output, tuple) else output
|
| 298 |
+
if flash_kernel_variant == "flash_attn3":
|
| 299 |
+
output = flash_kernel.flash_attn_func(
|
| 300 |
+
q=query_states,
|
| 301 |
+
k=key_states,
|
| 302 |
+
v=value_states,
|
| 303 |
+
softmax_scale=softmax_scale,
|
| 304 |
+
causal=causal,
|
| 305 |
+
)
|
| 306 |
+
if isinstance(output, tuple):
|
| 307 |
+
return output[0]
|
| 308 |
+
return output
|
| 309 |
+
raise RuntimeError(f"Unsupported FlashAttention kernel variant: {flash_kernel_variant}")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _kernels_flash_varlen_forward(
|
| 313 |
+
query_states: torch.Tensor,
|
| 314 |
+
key_states: torch.Tensor,
|
| 315 |
+
value_states: torch.Tensor,
|
| 316 |
+
cu_seqlens_q: torch.Tensor,
|
| 317 |
+
cu_seqlens_k: torch.Tensor,
|
| 318 |
+
max_seqlen_in_batch_q: int,
|
| 319 |
+
max_seqlen_in_batch_k: int,
|
| 320 |
+
causal: bool = False,
|
| 321 |
+
softmax_scale: float | None = None,
|
| 322 |
+
implementation: str = "flash_attention_3",
|
| 323 |
+
) -> torch.Tensor:
|
| 324 |
+
"""Varlen flash-attention forward, optionally overriding the softmax scale.
|
| 325 |
+
|
| 326 |
+
See `_kernels_flash_forward` docstring for why `softmax_scale=1.0` must be
|
| 327 |
+
passed when Q has been pre-scaled by the caller.
|
| 328 |
+
"""
|
| 329 |
+
flash_kernel, flash_kernel_variant = _ensure_flash_kernels_loaded(implementation)
|
| 330 |
+
if flash_kernel_variant == "flash_attn2":
|
| 331 |
+
output = flash_kernel.flash_attn_varlen_func(
|
| 332 |
+
q=query_states,
|
| 333 |
+
k=key_states,
|
| 334 |
+
v=value_states,
|
| 335 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 336 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 337 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 338 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 339 |
+
dropout_p=0.0,
|
| 340 |
+
softmax_scale=softmax_scale,
|
| 341 |
+
causal=causal,
|
| 342 |
+
)
|
| 343 |
+
return output[0] if isinstance(output, tuple) else output
|
| 344 |
+
if flash_kernel_variant == "flash_attn3":
|
| 345 |
+
output = flash_kernel.flash_attn_varlen_func(
|
| 346 |
+
q=query_states,
|
| 347 |
+
k=key_states,
|
| 348 |
+
v=value_states,
|
| 349 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 350 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 351 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 352 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 353 |
+
softmax_scale=softmax_scale,
|
| 354 |
+
causal=causal,
|
| 355 |
+
)
|
| 356 |
+
if isinstance(output, tuple):
|
| 357 |
+
return output[0]
|
| 358 |
+
return output
|
| 359 |
+
raise RuntimeError(f"Unsupported FlashAttention kernel variant: {flash_kernel_variant}")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# Varlen flash attention runs only on real tokens. These helpers remove padding
|
| 363 |
+
# before the kernel call and restore the original padded batch shape afterward.
|
| 364 |
+
class IndexFirstAxis(torch.autograd.Function):
|
| 365 |
+
@staticmethod
|
| 366 |
+
def forward(ctx, input, indices) -> torch.Tensor:
|
| 367 |
+
ctx.save_for_backward(indices)
|
| 368 |
+
if input.ndim < 2:
|
| 369 |
+
raise ValueError(
|
| 370 |
+
"index_first_axis input must have at least two dimensions; "
|
| 371 |
+
f"received shape {tuple(input.shape)}."
|
| 372 |
+
)
|
| 373 |
+
if indices.ndim != 1:
|
| 374 |
+
raise ValueError(
|
| 375 |
+
"index_first_axis indices must be one-dimensional; "
|
| 376 |
+
f"received shape {tuple(indices.shape)}."
|
| 377 |
+
)
|
| 378 |
+
ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:]
|
| 379 |
+
second_dim = other_shape.numel()
|
| 380 |
+
return torch.gather(
|
| 381 |
+
rearrange(input, "b ... -> b (...)"), 0, indices.unsqueeze(1).expand(-1, second_dim)
|
| 382 |
+
).reshape(-1, *other_shape)
|
| 383 |
+
|
| 384 |
+
@staticmethod
|
| 385 |
+
def backward(ctx, grad_output) -> tuple[torch.Tensor, None]:
|
| 386 |
+
(indices,) = ctx.saved_tensors
|
| 387 |
+
if grad_output.ndim < 2:
|
| 388 |
+
raise RuntimeError(
|
| 389 |
+
"index_first_axis received an invalid gradient with fewer than "
|
| 390 |
+
"two dimensions."
|
| 391 |
+
)
|
| 392 |
+
other_shape = grad_output.shape[1:]
|
| 393 |
+
grad_output = rearrange(grad_output, "b ... -> b (...)")
|
| 394 |
+
grad_input = torch.zeros(
|
| 395 |
+
[ctx.first_axis_dim, grad_output.shape[1]],
|
| 396 |
+
device=grad_output.device,
|
| 397 |
+
dtype=grad_output.dtype,
|
| 398 |
+
)
|
| 399 |
+
grad_input.scatter_(0, indices.unsqueeze(1).expand(-1, grad_output.shape[1]), grad_output)
|
| 400 |
+
return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class IndexPutFirstAxis(torch.autograd.Function):
|
| 404 |
+
@staticmethod
|
| 405 |
+
def forward(ctx, values, indices, first_axis_dim) -> torch.Tensor:
|
| 406 |
+
ctx.save_for_backward(indices)
|
| 407 |
+
if indices.ndim != 1:
|
| 408 |
+
raise ValueError(
|
| 409 |
+
"index_put_first_axis indices must be one-dimensional; "
|
| 410 |
+
f"received shape {tuple(indices.shape)}."
|
| 411 |
+
)
|
| 412 |
+
if values.ndim < 2:
|
| 413 |
+
raise ValueError(
|
| 414 |
+
"index_put_first_axis values must have at least two dimensions; "
|
| 415 |
+
f"received shape {tuple(values.shape)}."
|
| 416 |
+
)
|
| 417 |
+
output = torch.zeros(
|
| 418 |
+
first_axis_dim, *values.shape[1:], device=values.device, dtype=values.dtype
|
| 419 |
+
)
|
| 420 |
+
output[indices] = values
|
| 421 |
+
return output
|
| 422 |
+
|
| 423 |
+
@staticmethod
|
| 424 |
+
def backward(ctx, grad_output) -> tuple[torch.Tensor, None, None]:
|
| 425 |
+
(indices,) = ctx.saved_tensors
|
| 426 |
+
return grad_output[indices], None, None
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
index_first_axis = IndexFirstAxis.apply
|
| 430 |
+
index_put_first_axis = IndexPutFirstAxis.apply
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def pad_input(
|
| 434 |
+
hidden_states: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int
|
| 435 |
+
) -> torch.Tensor:
|
| 436 |
+
output = index_put_first_axis(hidden_states, indices, batch * seqlen)
|
| 437 |
+
return rearrange(output, "(b s) ... -> b s ...", b=batch)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _unpad_input(
|
| 441 |
+
query_layer: torch.Tensor,
|
| 442 |
+
key_layer: torch.Tensor,
|
| 443 |
+
value_layer: torch.Tensor,
|
| 444 |
+
attention_mask_2d: torch.Tensor,
|
| 445 |
+
) -> tuple[
|
| 446 |
+
torch.Tensor,
|
| 447 |
+
torch.Tensor,
|
| 448 |
+
torch.Tensor,
|
| 449 |
+
torch.Tensor,
|
| 450 |
+
tuple[torch.Tensor, torch.Tensor],
|
| 451 |
+
tuple[int, int],
|
| 452 |
+
]:
|
| 453 |
+
batch_size, seq_len, num_heads, head_dim = query_layer.shape
|
| 454 |
+
seqlens = attention_mask_2d.sum(dim=1).int()
|
| 455 |
+
cu_seqlens = F.pad(seqlens.cumsum(0, dtype=torch.int32), (1, 0))
|
| 456 |
+
max_seqlen = int(seqlens.max().item())
|
| 457 |
+
indices = attention_mask_2d.flatten().nonzero(as_tuple=False).flatten()
|
| 458 |
+
query_layer = index_first_axis(
|
| 459 |
+
query_layer.reshape(batch_size * seq_len, num_heads, head_dim), indices
|
| 460 |
+
)
|
| 461 |
+
key_layer = index_first_axis(
|
| 462 |
+
key_layer.reshape(batch_size * seq_len, num_heads, head_dim), indices
|
| 463 |
+
)
|
| 464 |
+
value_layer = index_first_axis(
|
| 465 |
+
value_layer.reshape(batch_size * seq_len, num_heads, head_dim), indices
|
| 466 |
+
)
|
| 467 |
+
return (
|
| 468 |
+
query_layer,
|
| 469 |
+
key_layer,
|
| 470 |
+
value_layer,
|
| 471 |
+
indices,
|
| 472 |
+
(cu_seqlens, cu_seqlens),
|
| 473 |
+
(max_seqlen, max_seqlen),
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _validate_flash_padding_mask(
|
| 478 |
+
query_states: torch.Tensor,
|
| 479 |
+
key_states: torch.Tensor,
|
| 480 |
+
value_states: torch.Tensor,
|
| 481 |
+
attention_mask_2d: torch.Tensor,
|
| 482 |
+
) -> torch.Tensor:
|
| 483 |
+
"""Validate the self-attention padding mask used by the varlen kernels."""
|
| 484 |
+
|
| 485 |
+
if attention_mask_2d.ndim != 2:
|
| 486 |
+
raise ValueError("FlashAttention padding masks must have shape (batch, sequence_length).")
|
| 487 |
+
expected_shape = query_states.shape[:2]
|
| 488 |
+
if tuple(attention_mask_2d.shape) != tuple(expected_shape):
|
| 489 |
+
raise ValueError(
|
| 490 |
+
"FlashAttention padding mask shape must match the query batch and "
|
| 491 |
+
f"sequence dimensions; expected {tuple(expected_shape)}, received "
|
| 492 |
+
f"{tuple(attention_mask_2d.shape)}."
|
| 493 |
+
)
|
| 494 |
+
if key_states.shape[:2] != expected_shape or value_states.shape[:2] != expected_shape:
|
| 495 |
+
raise ValueError(
|
| 496 |
+
"Masked FlashAttention requires Q, K, and V to share batch and sequence dimensions."
|
| 497 |
+
)
|
| 498 |
+
if attention_mask_2d.device != query_states.device:
|
| 499 |
+
raise ValueError("FlashAttention padding mask and Q, K, and V must be on the same device.")
|
| 500 |
+
return attention_mask_2d.to(dtype=torch.bool)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def kernels_flash_attention_func(
|
| 504 |
+
query_states: torch.Tensor,
|
| 505 |
+
key_states: torch.Tensor,
|
| 506 |
+
value_states: torch.Tensor,
|
| 507 |
+
attention_mask_2d: torch.Tensor | None = None,
|
| 508 |
+
causal: bool = False,
|
| 509 |
+
softmax_scale: float | None = None,
|
| 510 |
+
implementation: str = "flash_attention_3",
|
| 511 |
+
) -> torch.Tensor:
|
| 512 |
+
"""Public flash-attention entry point with optional padding handling.
|
| 513 |
+
|
| 514 |
+
`softmax_scale`:
|
| 515 |
+
None -> kernel applies its default `1 / sqrt(head_dim)`.
|
| 516 |
+
float -> kernel uses the given scale (pass 1.0 when Q is pre-scaled
|
| 517 |
+
by the caller).
|
| 518 |
+
|
| 519 |
+
Caller contract: if a model family pre-scales Q by `1/sqrt(head_dim)`
|
| 520 |
+
before calling this function (ESM2, DPLM, DPLM2, E1, and ESMFold do), pass
|
| 521 |
+
`softmax_scale=1.0`. Otherwise the flash kernel applies its default scale
|
| 522 |
+
again, yielding an effective `1/head_dim` scale that drifts across layers.
|
| 523 |
+
"""
|
| 524 |
+
_validate_kernels_flash_device(
|
| 525 |
+
query_states,
|
| 526 |
+
key_states,
|
| 527 |
+
value_states,
|
| 528 |
+
implementation,
|
| 529 |
+
)
|
| 530 |
+
runtime_dtype = _validate_kernels_flash_dtype(
|
| 531 |
+
query_states,
|
| 532 |
+
key_states,
|
| 533 |
+
value_states,
|
| 534 |
+
implementation,
|
| 535 |
+
)
|
| 536 |
+
if query_states.dtype != runtime_dtype:
|
| 537 |
+
query_states = query_states.to(dtype=runtime_dtype)
|
| 538 |
+
key_states = key_states.to(dtype=runtime_dtype)
|
| 539 |
+
value_states = value_states.to(dtype=runtime_dtype)
|
| 540 |
+
if attention_mask_2d is not None:
|
| 541 |
+
attention_mask_2d = _validate_flash_padding_mask(
|
| 542 |
+
query_states,
|
| 543 |
+
key_states,
|
| 544 |
+
value_states,
|
| 545 |
+
attention_mask_2d,
|
| 546 |
+
)
|
| 547 |
+
_ensure_flash_kernels_loaded(implementation)
|
| 548 |
+
if attention_mask_2d is not None:
|
| 549 |
+
batch_size, q_len = query_states.shape[:2]
|
| 550 |
+
(
|
| 551 |
+
query_states,
|
| 552 |
+
key_states,
|
| 553 |
+
value_states,
|
| 554 |
+
indices_q,
|
| 555 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 556 |
+
(max_seqlen_q, max_seqlen_k),
|
| 557 |
+
) = _unpad_input(query_states, key_states, value_states, attention_mask_2d)
|
| 558 |
+
attn_output_unpad = _kernels_flash_varlen_forward(
|
| 559 |
+
query_states=query_states,
|
| 560 |
+
key_states=key_states,
|
| 561 |
+
value_states=value_states,
|
| 562 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 563 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 564 |
+
max_seqlen_in_batch_q=max_seqlen_q,
|
| 565 |
+
max_seqlen_in_batch_k=max_seqlen_k,
|
| 566 |
+
causal=causal,
|
| 567 |
+
softmax_scale=softmax_scale,
|
| 568 |
+
implementation=implementation,
|
| 569 |
+
)
|
| 570 |
+
output = pad_input(attn_output_unpad, indices_q, batch_size, q_len)
|
| 571 |
+
return output.masked_fill(~attention_mask_2d[:, :, None, None], 0)
|
| 572 |
+
else:
|
| 573 |
+
return _kernels_flash_forward(
|
| 574 |
+
query_states=query_states,
|
| 575 |
+
key_states=key_states,
|
| 576 |
+
value_states=value_states,
|
| 577 |
+
causal=causal,
|
| 578 |
+
softmax_scale=softmax_scale,
|
| 579 |
+
implementation=implementation,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# User-facing backend strings follow the Transformers attention interface.
|
| 584 |
+
# Keep ``str`` plus ``Enum`` so stringification stays compatible with existing
|
| 585 |
+
# configuration serialization rather than adopting ``StrEnum.__str__``.
|
| 586 |
+
class AttentionBackend(str, Enum): # noqa: UP042
|
| 587 |
+
EAGER = "eager"
|
| 588 |
+
SDPA = "sdpa"
|
| 589 |
+
FLEX_ATTENTION = "flex_attention"
|
| 590 |
+
FLASH_ATTENTION_2 = "flash_attention_2"
|
| 591 |
+
FLASH_ATTENTION_3 = "flash_attention_3"
|
| 592 |
+
|
| 593 |
+
# Internal spelling retained to keep attention modules concise. It is an
|
| 594 |
+
# enum alias, not an accepted public backend string.
|
| 595 |
+
FLEX = FLEX_ATTENTION
|
| 596 |
+
|
| 597 |
+
@property
|
| 598 |
+
def is_flash(self) -> bool:
|
| 599 |
+
return self in {
|
| 600 |
+
AttentionBackend.FLASH_ATTENTION_2,
|
| 601 |
+
AttentionBackend.FLASH_ATTENTION_3,
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
VALID_ATTENTION_BACKENDS = tuple(b.value for b in AttentionBackend)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def warn_attention_backend_fallback(
|
| 609 |
+
requested_backend: str | AttentionBackend,
|
| 610 |
+
*,
|
| 611 |
+
effective_backend: str | AttentionBackend,
|
| 612 |
+
reason: str,
|
| 613 |
+
) -> None:
|
| 614 |
+
"""Warn when one forward call cannot honor the configured backend."""
|
| 615 |
+
|
| 616 |
+
requested = resolve_attention_backend(requested_backend).value
|
| 617 |
+
effective = resolve_attention_backend(effective_backend).value
|
| 618 |
+
if requested == effective:
|
| 619 |
+
return
|
| 620 |
+
warnings.warn(
|
| 621 |
+
f"{reason} The requested {requested!r} attention implementation cannot "
|
| 622 |
+
f"satisfy this call, so FastPLMs is using {effective!r} attention for this "
|
| 623 |
+
"call only. This can change performance and memory use; the configured "
|
| 624 |
+
"backend remains unchanged for subsequent calls.",
|
| 625 |
+
RuntimeWarning,
|
| 626 |
+
stacklevel=3,
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def resolve_attention_backend_for_call(
|
| 631 |
+
requested_backend: str | AttentionBackend,
|
| 632 |
+
*,
|
| 633 |
+
output_attentions: bool,
|
| 634 |
+
) -> AttentionBackend:
|
| 635 |
+
"""Resolve the effective backend for one call and report substitutions once."""
|
| 636 |
+
|
| 637 |
+
requested = resolve_attention_backend(requested_backend)
|
| 638 |
+
if not output_attentions or requested == AttentionBackend.EAGER:
|
| 639 |
+
return requested
|
| 640 |
+
warn_attention_backend_fallback(
|
| 641 |
+
requested,
|
| 642 |
+
effective_backend=AttentionBackend.EAGER,
|
| 643 |
+
reason=(
|
| 644 |
+
"output_attentions=True requires the full materialized attention probability "
|
| 645 |
+
"matrix, which optimized PyTorch attention APIs do not return."
|
| 646 |
+
),
|
| 647 |
+
)
|
| 648 |
+
return AttentionBackend.EAGER
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def resolve_attention_backend(
|
| 652 |
+
requested_backend: str | AttentionBackend | None,
|
| 653 |
+
) -> AttentionBackend:
|
| 654 |
+
"""Validate a backend without silently substituting another implementation."""
|
| 655 |
+
if requested_backend is None:
|
| 656 |
+
requested_backend = AttentionBackend.SDPA.value
|
| 657 |
+
if isinstance(requested_backend, AttentionBackend):
|
| 658 |
+
resolved = requested_backend
|
| 659 |
+
else:
|
| 660 |
+
try:
|
| 661 |
+
resolved = AttentionBackend(requested_backend)
|
| 662 |
+
except ValueError as error:
|
| 663 |
+
raise ValueError(
|
| 664 |
+
f"Unsupported attention implementation {requested_backend!r}; "
|
| 665 |
+
f"expected one of {VALID_ATTENTION_BACKENDS}."
|
| 666 |
+
) from error
|
| 667 |
+
if resolved == AttentionBackend.FLEX_ATTENTION and flex_attention is None:
|
| 668 |
+
raise RuntimeError(
|
| 669 |
+
"'flex_attention' was requested, but this PyTorch build does not provide it."
|
| 670 |
+
)
|
| 671 |
+
return resolved
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def get_attn_implementation(config) -> str:
|
| 675 |
+
"""Read the Transformers attention setting, defaulting to SDPA."""
|
| 676 |
+
requested = getattr(config, "_attn_implementation", None)
|
| 677 |
+
if requested is None:
|
| 678 |
+
requested = getattr(config, "attn_backend", None)
|
| 679 |
+
return resolve_attention_backend(requested).value
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def set_config_attn_implementation(config, implementation: str) -> str:
|
| 683 |
+
"""Set both the Transformers field and the internal dispatch field."""
|
| 684 |
+
resolved = resolve_attention_backend(implementation).value
|
| 685 |
+
if hasattr(config, "_attn_implementation_internal"):
|
| 686 |
+
config._attn_implementation_internal = resolved
|
| 687 |
+
else:
|
| 688 |
+
config._attn_implementation = resolved
|
| 689 |
+
# Existing checkpoint configs contain this field. Keeping it synchronized
|
| 690 |
+
# preserves their state schema while the public API uses attn_implementation.
|
| 691 |
+
config.attn_backend = resolved
|
| 692 |
+
return resolved
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
@torch.compiler.disable
|
| 696 |
+
def get_attention_mask(
|
| 697 |
+
effective_backend: AttentionBackend,
|
| 698 |
+
batch_size: int,
|
| 699 |
+
seq_len: int,
|
| 700 |
+
device: torch.device,
|
| 701 |
+
attention_mask: torch.Tensor | None = None,
|
| 702 |
+
dtype: torch.dtype | None = None,
|
| 703 |
+
mask_semantics: str = "padding",
|
| 704 |
+
) -> tuple[torch.Tensor | None, torch.Tensor | None, BlockMask | None]:
|
| 705 |
+
"""Build padding masks once for all encoder layers.
|
| 706 |
+
|
| 707 |
+
Returns (attention_mask_2d, attention_mask_4d, flex_block_mask).
|
| 708 |
+
"""
|
| 709 |
+
if attention_mask is None:
|
| 710 |
+
return None, None, None
|
| 711 |
+
|
| 712 |
+
if attention_mask.ndim != 2:
|
| 713 |
+
raise ValueError(
|
| 714 |
+
"attention_mask must have shape (batch, sequence_length); "
|
| 715 |
+
f"received rank {attention_mask.ndim} with shape {tuple(attention_mask.shape)}."
|
| 716 |
+
)
|
| 717 |
+
expected_shape = (batch_size, seq_len)
|
| 718 |
+
if tuple(attention_mask.shape) != expected_shape:
|
| 719 |
+
raise ValueError(
|
| 720 |
+
"attention_mask shape must match the input batch and sequence dimensions; "
|
| 721 |
+
f"expected {expected_shape}, received {tuple(attention_mask.shape)}."
|
| 722 |
+
)
|
| 723 |
+
attention_mask_2d = attention_mask.to(device=device, dtype=torch.bool)
|
| 724 |
+
if not bool(attention_mask_2d.any(dim=1).all()):
|
| 725 |
+
raise ValueError("attention_mask must keep at least one valid key per batch row.")
|
| 726 |
+
|
| 727 |
+
effective_backend = resolve_attention_backend(effective_backend)
|
| 728 |
+
|
| 729 |
+
if effective_backend.is_flash:
|
| 730 |
+
return attention_mask_2d, None, None
|
| 731 |
+
|
| 732 |
+
if effective_backend == AttentionBackend.FLEX_ATTENTION:
|
| 733 |
+
if create_block_mask is None:
|
| 734 |
+
raise RuntimeError(
|
| 735 |
+
"'flex_attention' was requested, but torch.create_block_mask is unavailable."
|
| 736 |
+
)
|
| 737 |
+
def mask_mod(batch_idx, head_idx, q_idx, kv_idx):
|
| 738 |
+
del head_idx, q_idx
|
| 739 |
+
# Match eager and SDPA: padding masks suppress invalid keys only.
|
| 740 |
+
# Invalid queries still attend to real keys and therefore remain
|
| 741 |
+
# finite; downstream residue masks exclude their outputs.
|
| 742 |
+
return attention_mask_2d[batch_idx, kv_idx]
|
| 743 |
+
|
| 744 |
+
flex_block_mask = _get_flex_block_mask(
|
| 745 |
+
mask_pattern=attention_mask_2d,
|
| 746 |
+
batch_size=batch_size,
|
| 747 |
+
query_length=seq_len,
|
| 748 |
+
key_value_length=seq_len,
|
| 749 |
+
device=device,
|
| 750 |
+
dtype=dtype,
|
| 751 |
+
mask_semantics=mask_semantics,
|
| 752 |
+
mask_mod=mask_mod,
|
| 753 |
+
)
|
| 754 |
+
return attention_mask_2d, None, flex_block_mask
|
| 755 |
+
|
| 756 |
+
# SDPA/manual masks only keys. Padding queries still attend to real keys, so
|
| 757 |
+
# their outputs stay finite instead of softmaxing over all -inf scores.
|
| 758 |
+
attention_mask_4d = attention_mask_2d[:, None, None, :]
|
| 759 |
+
return attention_mask_2d, attention_mask_4d, None
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def bool_to_additive_mask(
|
| 763 |
+
bool_mask: torch.Tensor,
|
| 764 |
+
dtype: torch.dtype,
|
| 765 |
+
) -> torch.Tensor:
|
| 766 |
+
"""Convert a bool mask (True = valid) to a float additive mask (0.0 valid, -inf invalid).
|
| 767 |
+
|
| 768 |
+
Why this exists: calling `bool_mask.masked_fill(bool_mask.logical_not(), float('-inf'))`
|
| 769 |
+
directly on a bool tensor returns a bool tensor because `-inf` casts to `True`.
|
| 770 |
+
That silently drops the mask. Always allocate a float tensor first, then fill it.
|
| 771 |
+
This helper is the sanctioned way to build an SDPA additive mask from a bool validity mask.
|
| 772 |
+
"""
|
| 773 |
+
if bool_mask.dtype != torch.bool:
|
| 774 |
+
raise TypeError(
|
| 775 |
+
f"bool_to_additive_mask requires a bool tensor, got dtype={bool_mask.dtype}"
|
| 776 |
+
)
|
| 777 |
+
additive = torch.zeros_like(bool_mask, dtype=dtype)
|
| 778 |
+
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 779 |
+
return additive
|
fastplms/attention/_kernel_lock.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resolve and validate Hugging Face kernels before importing their binaries."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib.metadata
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def require_kernels_package() -> None:
|
| 13 |
+
"""Fail early when the precompiled-kernel runtime is not installed."""
|
| 14 |
+
try:
|
| 15 |
+
import kernels # noqa: F401
|
| 16 |
+
except ImportError as error:
|
| 17 |
+
raise RuntimeError(
|
| 18 |
+
"Precompiled FlashAttention requires the FastPLMs 'flash' extra."
|
| 19 |
+
) from error
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _kernel_lock_path() -> Path:
|
| 23 |
+
"""Return the lock from an artifact, checkout, or installed distribution."""
|
| 24 |
+
source_path = Path(__file__).resolve()
|
| 25 |
+
candidates = [
|
| 26 |
+
source_path.parents[1] / "kernels.lock",
|
| 27 |
+
source_path.parents[3] / "kernels.lock",
|
| 28 |
+
]
|
| 29 |
+
try:
|
| 30 |
+
import fastplms
|
| 31 |
+
|
| 32 |
+
candidates.extend(Path(root) / "kernels.lock" for root in fastplms.__path__)
|
| 33 |
+
except (ImportError, AttributeError):
|
| 34 |
+
pass
|
| 35 |
+
for candidate in candidates:
|
| 36 |
+
if candidate.is_file():
|
| 37 |
+
return candidate
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
distribution = importlib.metadata.distribution("fastplms")
|
| 41 |
+
except importlib.metadata.PackageNotFoundError as error:
|
| 42 |
+
raise RuntimeError("FastPLMs was installed without kernels.lock.") from error
|
| 43 |
+
for relative in distribution.files or ():
|
| 44 |
+
if relative.name != "kernels.lock":
|
| 45 |
+
continue
|
| 46 |
+
candidate = Path(distribution.locate_file(relative))
|
| 47 |
+
if candidate.is_file():
|
| 48 |
+
return candidate
|
| 49 |
+
raise RuntimeError("The installed FastPLMs distribution does not contain kernels.lock.")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _locked_entry(lock_path: Path, repository: str) -> dict[str, Any]:
|
| 53 |
+
try:
|
| 54 |
+
data = json.loads(lock_path.read_text(encoding="utf-8"))
|
| 55 |
+
except (OSError, json.JSONDecodeError) as error:
|
| 56 |
+
raise RuntimeError(f"Unable to read the packaged kernel lock: {lock_path}") from error
|
| 57 |
+
if not isinstance(data, list):
|
| 58 |
+
raise RuntimeError("kernels.lock must contain a JSON list.")
|
| 59 |
+
if any(not isinstance(entry, dict) for entry in data):
|
| 60 |
+
raise RuntimeError("Every kernels.lock entry must be a JSON object.")
|
| 61 |
+
matches = [entry for entry in data if entry.get("repo_id") == repository]
|
| 62 |
+
if len(matches) != 1:
|
| 63 |
+
raise RuntimeError(
|
| 64 |
+
f"kernels.lock must contain exactly one entry for {repository!r}; found {len(matches)}."
|
| 65 |
+
)
|
| 66 |
+
return matches[0]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _offline_mode() -> bool:
|
| 70 |
+
"""Return whether Hub access was explicitly disabled for this process."""
|
| 71 |
+
|
| 72 |
+
enabled_values = {"1", "on", "true", "yes"}
|
| 73 |
+
return any(
|
| 74 |
+
os.environ.get(name, "").strip().lower() in enabled_values
|
| 75 |
+
for name in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE")
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _offline_snapshot_path(repository: str, revision: str) -> Path:
|
| 80 |
+
"""Locate one exact, possibly sparse, kernel snapshot without using Hub APIs."""
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
from huggingface_hub import constants
|
| 84 |
+
from huggingface_hub.file_download import repo_folder_name
|
| 85 |
+
except ImportError as error:
|
| 86 |
+
raise RuntimeError("Offline kernel loading requires huggingface-hub.") from error
|
| 87 |
+
|
| 88 |
+
cache_root = Path(os.environ.get("KERNELS_CACHE") or constants.HF_HUB_CACHE).resolve()
|
| 89 |
+
repository_root = (
|
| 90 |
+
cache_root / repo_folder_name(repo_id=repository, repo_type="kernel")
|
| 91 |
+
).resolve()
|
| 92 |
+
snapshot = repository_root / "snapshots" / revision
|
| 93 |
+
if not snapshot.is_dir():
|
| 94 |
+
raise RuntimeError(
|
| 95 |
+
f"The exact offline kernel snapshot {repository}@{revision} is not cached under "
|
| 96 |
+
f"{cache_root}. Run `kernels download` before enabling offline mode."
|
| 97 |
+
)
|
| 98 |
+
if repository_root not in snapshot.resolve().parents:
|
| 99 |
+
raise RuntimeError(f"Refusing kernel snapshot outside its cache repository: {snapshot}")
|
| 100 |
+
return snapshot
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _load_offline_locked_kernel(
|
| 104 |
+
repository: str,
|
| 105 |
+
revision: str,
|
| 106 |
+
variant_locks: dict[str, object],
|
| 107 |
+
) -> object:
|
| 108 |
+
"""Validate and import the one compatible variant from a sparse Hub snapshot."""
|
| 109 |
+
snapshot = _offline_snapshot_path(repository, revision)
|
| 110 |
+
build_root = snapshot / "build"
|
| 111 |
+
if not build_root.is_dir():
|
| 112 |
+
raise RuntimeError(f"The cached kernel snapshot has no build directory: {snapshot}")
|
| 113 |
+
|
| 114 |
+
cached_names = sorted(entry.name for entry in build_root.iterdir() if entry.is_dir())
|
| 115 |
+
unexpected = sorted(set(cached_names).difference(variant_locks))
|
| 116 |
+
if unexpected:
|
| 117 |
+
raise RuntimeError(
|
| 118 |
+
f"The cached {repository}@{revision} snapshot contains unlocked variants: "
|
| 119 |
+
f"{', '.join(unexpected)}"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
from kernels import get_local_kernel
|
| 124 |
+
from kernels.utils import validate_kernel
|
| 125 |
+
from kernels.variants import get_variants_local, resolve_variants
|
| 126 |
+
except ImportError as error:
|
| 127 |
+
raise RuntimeError(
|
| 128 |
+
"Precompiled FlashAttention requires the FastPLMs 'flash' extra."
|
| 129 |
+
) from error
|
| 130 |
+
|
| 131 |
+
parsed = get_variants_local(build_root)
|
| 132 |
+
parsed_names = {variant.variant_str for variant in parsed}
|
| 133 |
+
invalid = sorted(set(cached_names).difference(parsed_names))
|
| 134 |
+
if invalid:
|
| 135 |
+
raise RuntimeError(
|
| 136 |
+
f"The cached {repository}@{revision} snapshot contains invalid variants: "
|
| 137 |
+
f"{', '.join(invalid)}"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
compatible, _ = resolve_variants(parsed)
|
| 141 |
+
if len(compatible) != 1:
|
| 142 |
+
names = ", ".join(variant.variant_str for variant in compatible) or "none"
|
| 143 |
+
raise RuntimeError(
|
| 144 |
+
f"Expected exactly one compatible cached variant for {repository}@{revision}; "
|
| 145 |
+
f"found {names}."
|
| 146 |
+
)
|
| 147 |
+
variant_name = compatible[0].variant_str
|
| 148 |
+
variant_lock = variant_locks.get(variant_name)
|
| 149 |
+
expected_hash = getattr(variant_lock, "hash", None)
|
| 150 |
+
if not isinstance(expected_hash, str) or not expected_hash.startswith("sha256-"):
|
| 151 |
+
raise RuntimeError(f"The kernel lock for {variant_name} has no valid SHA-256 digest.")
|
| 152 |
+
|
| 153 |
+
# Hash validation deliberately happens before import. This operates on the
|
| 154 |
+
# sparse snapshot produced by `kernels download` and avoids Hub 1.23's
|
| 155 |
+
# full-snapshot completeness check in offline mode.
|
| 156 |
+
validate_kernel(repo_path=snapshot, variant=variant_name, hash=expected_hash)
|
| 157 |
+
return get_local_kernel(build_root / variant_name)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def load_locked_kernel(repository: str, revision: str) -> object:
|
| 161 |
+
"""Download, hash-validate, then import one immutable precompiled kernel."""
|
| 162 |
+
require_kernels_package()
|
| 163 |
+
try:
|
| 164 |
+
from kernels import get_local_kernel, install_kernel
|
| 165 |
+
from kernels.lockfile import KernelLock
|
| 166 |
+
except ImportError as error:
|
| 167 |
+
raise RuntimeError(
|
| 168 |
+
"Precompiled FlashAttention requires the FastPLMs 'flash' extra."
|
| 169 |
+
) from error
|
| 170 |
+
|
| 171 |
+
lock_path = _kernel_lock_path()
|
| 172 |
+
kernel_lock = KernelLock.from_json(_locked_entry(lock_path, repository))
|
| 173 |
+
if kernel_lock.sha != revision:
|
| 174 |
+
raise RuntimeError(
|
| 175 |
+
f"The typed manifest pins {repository}@{revision}, but kernels.lock pins "
|
| 176 |
+
f"{kernel_lock.sha}."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
if _offline_mode():
|
| 180 |
+
return _load_offline_locked_kernel(repository, revision, kernel_lock.variants)
|
| 181 |
+
|
| 182 |
+
# `install_kernel` downloads data without importing it and validates the
|
| 183 |
+
# selected build against the tracked variant hash. Only then is the exact
|
| 184 |
+
# validated path imported directly. Offline mode uses the sparse-cache
|
| 185 |
+
# resolver above because Hub 1.23 rejects partial snapshots as incomplete.
|
| 186 |
+
validated_path = install_kernel(
|
| 187 |
+
repository,
|
| 188 |
+
revision=kernel_lock.sha,
|
| 189 |
+
variant_locks=kernel_lock.variants,
|
| 190 |
+
)
|
| 191 |
+
return get_local_kernel(validated_path)
|
fastplms/attention/interfaces.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers-compatible attention selection for FastPLMs models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Mapping
|
| 6 |
+
from functools import partial
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from transformers import AttentionInterface, AttentionMaskInterface
|
| 11 |
+
|
| 12 |
+
from ._core import (
|
| 13 |
+
AttentionBackend,
|
| 14 |
+
get_attn_implementation,
|
| 15 |
+
kernels_flash_attention_func,
|
| 16 |
+
resolve_attention_backend,
|
| 17 |
+
set_config_attn_implementation,
|
| 18 |
+
)
|
| 19 |
+
from ._kernel_lock import require_kernels_package
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _kernels_attention_forward(
|
| 23 |
+
module: torch.nn.Module,
|
| 24 |
+
query: torch.Tensor,
|
| 25 |
+
key: torch.Tensor,
|
| 26 |
+
value: torch.Tensor,
|
| 27 |
+
attention_mask: torch.Tensor | None,
|
| 28 |
+
*,
|
| 29 |
+
implementation: str,
|
| 30 |
+
**kwargs: Any,
|
| 31 |
+
) -> tuple[torch.Tensor, None]:
|
| 32 |
+
"""Run one canonical FlashAttention backend through Hugging Face kernels.
|
| 33 |
+
|
| 34 |
+
Transformers attention functions receive Q, K, and V with shape
|
| 35 |
+
(b, h, l, d) and return an output with shape (b, l, h, d). The shared
|
| 36 |
+
FastPLMs kernel adapter uses the latter layout internally.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
dropout = float(kwargs.get("dropout", 0.0) or 0.0)
|
| 40 |
+
if module.training and dropout:
|
| 41 |
+
raise RuntimeError(
|
| 42 |
+
"Hugging Face kernels FlashAttention is inference-only when attention dropout "
|
| 43 |
+
"is nonzero. Use SDPA for this training configuration."
|
| 44 |
+
)
|
| 45 |
+
causal = bool(kwargs.get("is_causal", getattr(module, "is_causal", False)))
|
| 46 |
+
softmax_scale = kwargs.get("scaling")
|
| 47 |
+
output = kernels_flash_attention_func(
|
| 48 |
+
query_states=query.transpose(1, 2).contiguous(),
|
| 49 |
+
key_states=key.transpose(1, 2).contiguous(),
|
| 50 |
+
value_states=value.transpose(1, 2).contiguous(),
|
| 51 |
+
attention_mask_2d=attention_mask,
|
| 52 |
+
causal=causal,
|
| 53 |
+
softmax_scale=softmax_scale,
|
| 54 |
+
implementation=implementation,
|
| 55 |
+
)
|
| 56 |
+
return output, None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Keep FastPLMs' kernels-only adapters local to this registry instance.
|
| 60 |
+
# ``GeneralInterface.register`` updates Transformers' class-wide mapping, so
|
| 61 |
+
# using it here would replace the canonical FlashAttention handlers for every
|
| 62 |
+
# model in the process, including models unrelated to FastPLMs.
|
| 63 |
+
FASTPLMS_ATTENTION_FUNCTIONS = AttentionInterface()
|
| 64 |
+
FASTPLMS_ATTENTION_MASKS = AttentionMaskInterface()
|
| 65 |
+
FASTPLMS_ATTENTION_FUNCTIONS["flash_attention_2"] = partial(
|
| 66 |
+
_kernels_attention_forward,
|
| 67 |
+
implementation="flash_attention_2",
|
| 68 |
+
)
|
| 69 |
+
FASTPLMS_ATTENTION_FUNCTIONS["flash_attention_3"] = partial(
|
| 70 |
+
_kernels_attention_forward,
|
| 71 |
+
implementation="flash_attention_3",
|
| 72 |
+
)
|
| 73 |
+
for _flash_name in ("flash_attention_2", "flash_attention_3"):
|
| 74 |
+
FASTPLMS_ATTENTION_MASKS[_flash_name] = FASTPLMS_ATTENTION_MASKS[_flash_name]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class FastPLMsAttentionMixin:
|
| 78 |
+
"""Synchronize Transformers attention selection with custom model layers.
|
| 79 |
+
|
| 80 |
+
Model families retain their checkpoint parameter names. Only runtime
|
| 81 |
+
attributes are updated when ``set_attn_implementation`` is called.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
_supports_sdpa = True
|
| 85 |
+
_supports_flex_attn = True
|
| 86 |
+
# Transformers 5.13 uses the singular flag during model construction. A
|
| 87 |
+
# family opts in only when its manifest entry advertises at least one of
|
| 88 |
+
# the two FastPLMs kernels-only FlashAttention implementations.
|
| 89 |
+
_supports_flash_attn = False
|
| 90 |
+
_supports_flash_attn_2 = False
|
| 91 |
+
_supports_flash_attn_3 = False
|
| 92 |
+
_fastplms_attention_implementations = (
|
| 93 |
+
"eager",
|
| 94 |
+
"sdpa",
|
| 95 |
+
"flex_attention",
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def _validate_attention_name(self, implementation: str) -> None:
|
| 99 |
+
if implementation not in self._fastplms_attention_implementations:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
f"{type(self).__name__} does not support {implementation!r}; expected one of "
|
| 102 |
+
f"{self._fastplms_attention_implementations}."
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def _check_and_adjust_attn_implementation(
|
| 106 |
+
self,
|
| 107 |
+
attn_implementation: str | None,
|
| 108 |
+
is_init_check: bool = False,
|
| 109 |
+
allow_all_kernels: bool = False,
|
| 110 |
+
) -> str:
|
| 111 |
+
"""Resolve attention without invoking Transformers' source-Flash probe.
|
| 112 |
+
|
| 113 |
+
The standard ``flash_attention_2`` and ``flash_attention_3`` names are
|
| 114 |
+
retained for the Transformers API, but FastPLMs resolves them only
|
| 115 |
+
through the exact Hugging Face ``kernels`` artifacts pinned by
|
| 116 |
+
``models.toml``. Repository-qualified or otherwise external kernels
|
| 117 |
+
are never accepted through this model hook.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
if allow_all_kernels:
|
| 121 |
+
raise ValueError("FastPLMs does not load external attention kernels.")
|
| 122 |
+
if attn_implementation is None:
|
| 123 |
+
return super()._check_and_adjust_attn_implementation(
|
| 124 |
+
None,
|
| 125 |
+
is_init_check=is_init_check,
|
| 126 |
+
allow_all_kernels=False,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
self._validate_attention_name(attn_implementation)
|
| 130 |
+
if attn_implementation in {"flash_attention_2", "flash_attention_3"}:
|
| 131 |
+
if not self._supports_flash_attn:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"{type(self).__name__} does not advertise kernels-only FlashAttention."
|
| 134 |
+
)
|
| 135 |
+
# Validate the lightweight Python dependency here, but defer binary
|
| 136 |
+
# download and import until Q, K, and V have passed the CUDA gate.
|
| 137 |
+
require_kernels_package()
|
| 138 |
+
return attn_implementation
|
| 139 |
+
|
| 140 |
+
return super()._check_and_adjust_attn_implementation(
|
| 141 |
+
attn_implementation,
|
| 142 |
+
is_init_check=is_init_check,
|
| 143 |
+
allow_all_kernels=False,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def __init__(self, config, *args: Any, **kwargs: Any) -> None:
|
| 147 |
+
sentinel = object()
|
| 148 |
+
internal = getattr(config, "_attn_implementation_internal", sentinel)
|
| 149 |
+
canonical = (
|
| 150 |
+
getattr(config, "_attn_implementation", None) if internal is sentinel else internal
|
| 151 |
+
)
|
| 152 |
+
legacy = getattr(config, "attn_backend", None)
|
| 153 |
+
requested = canonical if canonical is not None else legacy
|
| 154 |
+
if requested is not None:
|
| 155 |
+
if not isinstance(requested, str):
|
| 156 |
+
raise TypeError(
|
| 157 |
+
"The configured attention implementation must be a string or None; "
|
| 158 |
+
f"received {type(requested).__name__}."
|
| 159 |
+
)
|
| 160 |
+
self._validate_attention_name(requested)
|
| 161 |
+
# ``PreTrainedModel.__init__`` resolves a missing Transformers
|
| 162 |
+
# implementation to the family default. Legacy FastPLMs configs
|
| 163 |
+
# persist their explicit choice in ``attn_backend``, so forward it
|
| 164 |
+
# into the canonical Transformers field before the base class can
|
| 165 |
+
# replace it with SDPA. A non-None canonical value still wins,
|
| 166 |
+
# including an explicit ``attn_implementation=...`` load override.
|
| 167 |
+
if canonical is None and legacy is not None:
|
| 168 |
+
set_config_attn_implementation(config, legacy)
|
| 169 |
+
super().__init__(config, *args, **kwargs)
|
| 170 |
+
# Transformers resolves an unspecified implementation during the base
|
| 171 |
+
# model initialization. Synchronize that choice before family layers
|
| 172 |
+
# are constructed.
|
| 173 |
+
resolved = get_attn_implementation(config)
|
| 174 |
+
self._validate_attention_name(resolved)
|
| 175 |
+
set_config_attn_implementation(config, resolved)
|
| 176 |
+
|
| 177 |
+
def set_attn_implementation(
|
| 178 |
+
self,
|
| 179 |
+
attn_implementation: str | Mapping[str, str],
|
| 180 |
+
allow_all_kernels: bool = False,
|
| 181 |
+
) -> None:
|
| 182 |
+
"""Select an advertised backend and update every instantiated layer."""
|
| 183 |
+
if isinstance(attn_implementation, Mapping):
|
| 184 |
+
if set(attn_implementation) == {""}:
|
| 185 |
+
attn_implementation = attn_implementation[""]
|
| 186 |
+
else:
|
| 187 |
+
raise ValueError(
|
| 188 |
+
"FastPLMs models have one attention backbone; pass a string or {'': name}."
|
| 189 |
+
)
|
| 190 |
+
resolved_name = self._check_and_adjust_attn_implementation(
|
| 191 |
+
attn_implementation,
|
| 192 |
+
is_init_check=False,
|
| 193 |
+
allow_all_kernels=allow_all_kernels,
|
| 194 |
+
)
|
| 195 |
+
set_config_attn_implementation(self.config, resolved_name)
|
| 196 |
+
resolved = resolve_attention_backend(resolved_name)
|
| 197 |
+
for module in self.modules():
|
| 198 |
+
if module is self:
|
| 199 |
+
continue
|
| 200 |
+
for attribute in ("attn_backend", "attention_backend", "_attn_backend"):
|
| 201 |
+
if attribute not in module.__dict__:
|
| 202 |
+
continue
|
| 203 |
+
current = module.__dict__[attribute]
|
| 204 |
+
module.__dict__[attribute] = (
|
| 205 |
+
resolved if isinstance(current, AttentionBackend) else resolved_name
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def validate_transformers_attention_interfaces() -> None:
|
| 210 |
+
"""Verify that Transformers exposes functions and masks for every backend.
|
| 211 |
+
|
| 212 |
+
Transformers 5.13 registers these canonical names. The FastPLMs function
|
| 213 |
+
overrides remain instance-local and do not replace process-global handlers.
|
| 214 |
+
"""
|
| 215 |
+
function_registry = FASTPLMS_ATTENTION_FUNCTIONS
|
| 216 |
+
mask_registry = FASTPLMS_ATTENTION_MASKS
|
| 217 |
+
missing_functions = [
|
| 218 |
+
name
|
| 219 |
+
for name in (
|
| 220 |
+
"sdpa",
|
| 221 |
+
"flex_attention",
|
| 222 |
+
"flash_attention_2",
|
| 223 |
+
"flash_attention_3",
|
| 224 |
+
)
|
| 225 |
+
if name not in function_registry
|
| 226 |
+
]
|
| 227 |
+
missing_masks = [
|
| 228 |
+
name
|
| 229 |
+
for name in (
|
| 230 |
+
"eager",
|
| 231 |
+
"sdpa",
|
| 232 |
+
"flex_attention",
|
| 233 |
+
"flash_attention_2",
|
| 234 |
+
"flash_attention_3",
|
| 235 |
+
)
|
| 236 |
+
if name not in mask_registry
|
| 237 |
+
]
|
| 238 |
+
if missing_functions or missing_masks:
|
| 239 |
+
raise RuntimeError(
|
| 240 |
+
"Transformers attention registry is incomplete: "
|
| 241 |
+
f"functions={missing_functions}, masks={missing_masks}."
|
| 242 |
+
)
|
fastplms/embeddings/__init__.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ordered, residue-aware protein embedding utilities."""
|
| 2 |
+
|
| 3 |
+
from .pooling import POOLING_NAMES, Pooler, pagerank_weights
|
| 4 |
+
from .runner import (
|
| 5 |
+
EmbeddingMixin,
|
| 6 |
+
embed_dataset,
|
| 7 |
+
iter_fasta,
|
| 8 |
+
parse_fasta,
|
| 9 |
+
select_hidden_state_embeddings,
|
| 10 |
+
)
|
| 11 |
+
from .storage import (
|
| 12 |
+
DEFAULT_SHARD_SIZE,
|
| 13 |
+
append_sqlite_records,
|
| 14 |
+
convert_legacy_sqlite,
|
| 15 |
+
garbage_collect_safetensors_generations,
|
| 16 |
+
initialize_sqlite_run,
|
| 17 |
+
load_legacy_pth,
|
| 18 |
+
load_result,
|
| 19 |
+
load_safetensors_result,
|
| 20 |
+
load_sqlite_result,
|
| 21 |
+
save_result,
|
| 22 |
+
save_safetensors_result,
|
| 23 |
+
save_sqlite_result,
|
| 24 |
+
tensor_sha256,
|
| 25 |
+
update_sqlite_run_metadata,
|
| 26 |
+
)
|
| 27 |
+
from .types import (
|
| 28 |
+
EmbeddingBatch,
|
| 29 |
+
EmbeddingInput,
|
| 30 |
+
EmbeddingRecord,
|
| 31 |
+
EmbeddingResult,
|
| 32 |
+
LazyTensorReference,
|
| 33 |
+
TensorValue,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
"DEFAULT_SHARD_SIZE",
|
| 38 |
+
"POOLING_NAMES",
|
| 39 |
+
"EmbeddingBatch",
|
| 40 |
+
"EmbeddingInput",
|
| 41 |
+
"EmbeddingMixin",
|
| 42 |
+
"EmbeddingRecord",
|
| 43 |
+
"EmbeddingResult",
|
| 44 |
+
"LazyTensorReference",
|
| 45 |
+
"Pooler",
|
| 46 |
+
"TensorValue",
|
| 47 |
+
"append_sqlite_records",
|
| 48 |
+
"convert_legacy_sqlite",
|
| 49 |
+
"embed_dataset",
|
| 50 |
+
"garbage_collect_safetensors_generations",
|
| 51 |
+
"initialize_sqlite_run",
|
| 52 |
+
"iter_fasta",
|
| 53 |
+
"load_legacy_pth",
|
| 54 |
+
"load_result",
|
| 55 |
+
"load_safetensors_result",
|
| 56 |
+
"load_sqlite_result",
|
| 57 |
+
"pagerank_weights",
|
| 58 |
+
"parse_fasta",
|
| 59 |
+
"save_result",
|
| 60 |
+
"save_safetensors_result",
|
| 61 |
+
"save_sqlite_result",
|
| 62 |
+
"select_hidden_state_embeddings",
|
| 63 |
+
"tensor_sha256",
|
| 64 |
+
"update_sqlite_run_metadata",
|
| 65 |
+
]
|
fastplms/embeddings/pooling.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Residue-aware pooling implemented entirely with PyTorch."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
POOLING_NAMES = frozenset({"mean", "max", "norm", "median", "std", "var", "cls", "parti"})
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _validate_inputs(X: Tensor, M: Tensor) -> Tensor:
|
| 15 |
+
if not isinstance(X, Tensor) or not isinstance(M, Tensor):
|
| 16 |
+
raise TypeError("X and M must be tensors.")
|
| 17 |
+
if X.ndim != 3:
|
| 18 |
+
raise ValueError(f"X must have shape (b, l, d), got {tuple(X.shape)}.")
|
| 19 |
+
if not X.is_floating_point():
|
| 20 |
+
raise TypeError("X must use a floating-point embedding dtype.")
|
| 21 |
+
if M.shape != X.shape[:2]:
|
| 22 |
+
raise ValueError(f"M must have shape (b, l)={tuple(X.shape[:2])}, got {tuple(M.shape)}.")
|
| 23 |
+
if M.is_complex():
|
| 24 |
+
raise TypeError("M must be a boolean or binary numeric residue mask.")
|
| 25 |
+
if not bool(torch.isfinite(M).all()) or not bool(((M == 0) | (M == 1)).all()):
|
| 26 |
+
raise ValueError("M must contain only finite binary mask values.")
|
| 27 |
+
M = M.to(device=X.device, dtype=torch.bool)
|
| 28 |
+
if not bool(M.any(dim=1).all()):
|
| 29 |
+
raise ValueError("Every sample must contain at least one biological residue.")
|
| 30 |
+
if not bool((torch.isfinite(X) | ~M.unsqueeze(-1)).all()):
|
| 31 |
+
raise ValueError("Biological residue embeddings produced non-finite output.")
|
| 32 |
+
return M
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _pooled_attention(attentions: Tensor | Sequence[Tensor], *, batch_size: int) -> Tensor:
|
| 36 |
+
"""Max-pool layer/head attention A to shape ``(b, l, l)``.
|
| 37 |
+
|
| 38 |
+
``parti`` historically keeps the strongest directed edge across the
|
| 39 |
+
available attention maps before PageRank. Replacing NetworkX with Torch
|
| 40 |
+
must not change that reduction.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
if isinstance(attentions, Sequence):
|
| 44 |
+
if not attentions:
|
| 45 |
+
raise ValueError("parti received an empty attention sequence.")
|
| 46 |
+
# Each A_i has shape (b, h, l, l).
|
| 47 |
+
A = torch.stack(tuple(attentions), dim=1)
|
| 48 |
+
else:
|
| 49 |
+
A = attentions
|
| 50 |
+
|
| 51 |
+
if A.ndim == 5:
|
| 52 |
+
if A.shape[0] != batch_size and A.shape[1] == batch_size:
|
| 53 |
+
A = A.transpose(0, 1)
|
| 54 |
+
if A.shape[0] != batch_size:
|
| 55 |
+
raise ValueError("Five-dimensional attentions must use (b, n, h, l, l).")
|
| 56 |
+
A = A.flatten(1, 2).amax(dim=1)
|
| 57 |
+
elif A.ndim == 4:
|
| 58 |
+
if A.shape[0] != batch_size:
|
| 59 |
+
raise ValueError("Four-dimensional attentions must use (b, h, l, l).")
|
| 60 |
+
A = A.amax(dim=1)
|
| 61 |
+
elif A.ndim == 3:
|
| 62 |
+
if A.shape[0] != batch_size:
|
| 63 |
+
raise ValueError("Three-dimensional attentions must use (b, l, l).")
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError("Attentions must have shape (b, l, l), (b, h, l, l), or (b, n, h, l, l).")
|
| 66 |
+
return A
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def pagerank_weights(
|
| 70 |
+
A: Tensor,
|
| 71 |
+
*,
|
| 72 |
+
damping: float = 0.85,
|
| 73 |
+
tolerance: float = 1e-6,
|
| 74 |
+
max_iterations: int = 100,
|
| 75 |
+
) -> Tensor:
|
| 76 |
+
"""Compute PageRank weights for a non-negative attention matrix A.
|
| 77 |
+
|
| 78 |
+
A has shape ``(l, l)``. Rows are normalized into transition
|
| 79 |
+
probabilities; dangling rows transition uniformly.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
if not isinstance(A, Tensor):
|
| 83 |
+
raise TypeError("A must be a tensor.")
|
| 84 |
+
if A.ndim != 2 or A.shape[0] != A.shape[1]:
|
| 85 |
+
raise ValueError(f"A must be square, got shape {tuple(A.shape)}.")
|
| 86 |
+
if not A.is_floating_point():
|
| 87 |
+
raise TypeError("A must use a floating-point attention dtype.")
|
| 88 |
+
if not isinstance(damping, (int, float)) or isinstance(damping, bool):
|
| 89 |
+
raise TypeError("damping must be a finite float in [0, 1).")
|
| 90 |
+
if not math.isfinite(float(damping)) or not 0 <= damping < 1:
|
| 91 |
+
raise ValueError("damping must be a finite float in [0, 1).")
|
| 92 |
+
if not isinstance(tolerance, (int, float)) or isinstance(tolerance, bool):
|
| 93 |
+
raise TypeError("tolerance must be a positive finite float.")
|
| 94 |
+
if not math.isfinite(float(tolerance)) or tolerance <= 0:
|
| 95 |
+
raise ValueError("tolerance must be a positive finite float.")
|
| 96 |
+
if not isinstance(max_iterations, int) or isinstance(max_iterations, bool):
|
| 97 |
+
raise TypeError("max_iterations must be a positive integer.")
|
| 98 |
+
if max_iterations <= 0:
|
| 99 |
+
raise ValueError("max_iterations must be a positive integer.")
|
| 100 |
+
length = A.shape[0]
|
| 101 |
+
if length == 0:
|
| 102 |
+
raise ValueError("PageRank requires at least one residue.")
|
| 103 |
+
if not bool(torch.isfinite(A).all()):
|
| 104 |
+
raise ValueError("A must contain only finite attention values.")
|
| 105 |
+
work_dtype = torch.float64 if A.dtype == torch.float64 else torch.float32
|
| 106 |
+
P = A.detach().to(dtype=work_dtype).clamp_min(0)
|
| 107 |
+
row_sum = P.sum(dim=-1, keepdim=True)
|
| 108 |
+
uniform = torch.full_like(P, 1.0 / length)
|
| 109 |
+
P = torch.where(row_sum > 0, P / row_sum.clamp_min(torch.finfo(work_dtype).tiny), uniform)
|
| 110 |
+
p = torch.full((length,), 1.0 / length, device=P.device, dtype=work_dtype)
|
| 111 |
+
teleport = (1.0 - damping) / length
|
| 112 |
+
for _ in range(max_iterations):
|
| 113 |
+
p_next = teleport + damping * (P.transpose(0, 1) @ p)
|
| 114 |
+
if torch.linalg.vector_norm(p_next - p, ord=1) <= tolerance:
|
| 115 |
+
p = p_next
|
| 116 |
+
break
|
| 117 |
+
p = p_next
|
| 118 |
+
return p / p.sum()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Pooler:
|
| 122 |
+
"""Apply one or more pooling operations to biological residue rows."""
|
| 123 |
+
|
| 124 |
+
def __init__(self, pooling: str | Sequence[str] = ("mean",)) -> None:
|
| 125 |
+
pooling_value: object = pooling
|
| 126 |
+
if isinstance(pooling_value, (bytes, bytearray)) or not isinstance(
|
| 127 |
+
pooling_value, (str, Sequence)
|
| 128 |
+
):
|
| 129 |
+
raise TypeError("pooling must be a name or a sequence of names.")
|
| 130 |
+
names = (pooling_value,) if isinstance(pooling_value, str) else tuple(pooling_value)
|
| 131 |
+
if not all(isinstance(name, str) for name in names):
|
| 132 |
+
raise TypeError("pooling names must be strings.")
|
| 133 |
+
if not names:
|
| 134 |
+
raise ValueError("At least one pooling operation is required.")
|
| 135 |
+
unknown = set(names) - POOLING_NAMES
|
| 136 |
+
if unknown:
|
| 137 |
+
raise ValueError(f"Unknown pooling operations: {sorted(unknown)}.")
|
| 138 |
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
| 139 |
+
if duplicates:
|
| 140 |
+
raise ValueError(f"Duplicate pooling operations are not supported: {duplicates}.")
|
| 141 |
+
self.names = names
|
| 142 |
+
|
| 143 |
+
def output_slices(self, d: int) -> dict[str, tuple[int, int]]:
|
| 144 |
+
"""Return the output interval assigned to each pooler."""
|
| 145 |
+
|
| 146 |
+
if not isinstance(d, int) or isinstance(d, bool):
|
| 147 |
+
raise TypeError("d must be a positive integer.")
|
| 148 |
+
if d <= 0:
|
| 149 |
+
raise ValueError("d must be a positive integer.")
|
| 150 |
+
return {name: (i * d, (i + 1) * d) for i, name in enumerate(self.names)}
|
| 151 |
+
|
| 152 |
+
def __call__(
|
| 153 |
+
self,
|
| 154 |
+
X: Tensor,
|
| 155 |
+
residue_mask: Tensor,
|
| 156 |
+
*,
|
| 157 |
+
attentions: Tensor | Sequence[Tensor] | None = None,
|
| 158 |
+
attention_backend: str | None = None,
|
| 159 |
+
) -> Tensor:
|
| 160 |
+
M = _validate_inputs(X, residue_mask)
|
| 161 |
+
M_expanded = M.unsqueeze(-1)
|
| 162 |
+
count = M_expanded.sum(dim=1).clamp_min(1)
|
| 163 |
+
X_residues = X.masked_fill(~M_expanded, 0)
|
| 164 |
+
outputs: list[Tensor] = []
|
| 165 |
+
|
| 166 |
+
for name in self.names:
|
| 167 |
+
if name == "mean":
|
| 168 |
+
Y = X_residues.sum(dim=1) / count
|
| 169 |
+
elif name == "max":
|
| 170 |
+
Y = X.masked_fill(~M_expanded, -torch.inf).max(dim=1).values
|
| 171 |
+
elif name == "norm":
|
| 172 |
+
Y = torch.linalg.vector_norm(X_residues, ord=2, dim=1)
|
| 173 |
+
elif name == "median":
|
| 174 |
+
Y = X.masked_fill(~M_expanded, torch.nan).nanmedian(dim=1).values
|
| 175 |
+
elif name in {"var", "std"}:
|
| 176 |
+
mean = X_residues.sum(dim=1, keepdim=True) / count.unsqueeze(1)
|
| 177 |
+
centered = (X - mean).masked_fill(~M_expanded, 0)
|
| 178 |
+
variance = (centered**2).sum(dim=1) / count
|
| 179 |
+
Y = variance.sqrt() if name == "std" else variance
|
| 180 |
+
elif name == "cls":
|
| 181 |
+
Y = X[:, 0]
|
| 182 |
+
else:
|
| 183 |
+
if attention_backend != "eager":
|
| 184 |
+
raise ValueError(
|
| 185 |
+
"parti requires attn_implementation='eager' so full "
|
| 186 |
+
"attention matrices are available."
|
| 187 |
+
)
|
| 188 |
+
if attentions is None:
|
| 189 |
+
raise ValueError("parti requires model attention matrices.")
|
| 190 |
+
if int(M.sum(dim=1).max().item()) > 2048:
|
| 191 |
+
raise ValueError("parti supports at most 2,048 biological residues.")
|
| 192 |
+
A = _pooled_attention(attentions, batch_size=X.shape[0]).to(X.device)
|
| 193 |
+
pooled: list[Tensor] = []
|
| 194 |
+
for X_i, M_i, A_i in zip(X, M, A, strict=True):
|
| 195 |
+
indices = M_i.nonzero(as_tuple=True)[0]
|
| 196 |
+
A_residue = A_i.index_select(0, indices).index_select(1, indices)
|
| 197 |
+
w = pagerank_weights(A_residue).to(dtype=X.dtype)
|
| 198 |
+
pooled.append(w @ X_i.index_select(0, indices))
|
| 199 |
+
Y = torch.stack(pooled)
|
| 200 |
+
if not bool(torch.isfinite(Y).all()):
|
| 201 |
+
raise ValueError(
|
| 202 |
+
f"Pooling operation {name!r} produced non-finite output from "
|
| 203 |
+
"biological residue embeddings."
|
| 204 |
+
)
|
| 205 |
+
outputs.append(Y)
|
| 206 |
+
|
| 207 |
+
return torch.cat(outputs, dim=-1)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
__all__ = ["POOLING_NAMES", "Pooler", "pagerank_weights"]
|
fastplms/embeddings/runner.py
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model-independent dataset embedding orchestration."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import platform
|
| 8 |
+
import sqlite3
|
| 9 |
+
import tempfile
|
| 10 |
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, overload
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
|
| 18 |
+
from .pooling import Pooler
|
| 19 |
+
from .storage import (
|
| 20 |
+
SafetensorsStreamWriter,
|
| 21 |
+
append_sqlite_records,
|
| 22 |
+
initialize_sqlite_run,
|
| 23 |
+
load_result,
|
| 24 |
+
load_sqlite_result,
|
| 25 |
+
safetensors_result_exists,
|
| 26 |
+
save_result,
|
| 27 |
+
tensor_sha256,
|
| 28 |
+
update_sqlite_run_metadata,
|
| 29 |
+
)
|
| 30 |
+
from .types import (
|
| 31 |
+
EmbeddingBatch,
|
| 32 |
+
EmbeddingInput,
|
| 33 |
+
EmbeddingRecord,
|
| 34 |
+
EmbeddingResult,
|
| 35 |
+
LazyTensorReference,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
_MAX_PARTI_RESIDUES = 2_048
|
| 39 |
+
_RUN_FINGERPRINT_SCHEMA_VERSION = 3
|
| 40 |
+
_MODEL_STATE_HASH_CHUNK_BYTES = 16 * 1024**2
|
| 41 |
+
_DEFAULT_BATCH_WINDOW_MULTIPLIER = 16
|
| 42 |
+
_SUPPORTED_STORAGE_FORMATS = frozenset({"safetensors", "sqlite"})
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _validate_parti_length(M: Tensor) -> None:
|
| 46 |
+
"""Reject an oversized attention graph before model inference."""
|
| 47 |
+
|
| 48 |
+
n_residues = int(M.to(dtype=torch.int64).sum(dim=1).max().item())
|
| 49 |
+
if n_residues > _MAX_PARTI_RESIDUES:
|
| 50 |
+
raise ValueError(f"parti supports at most {_MAX_PARTI_RESIDUES:,} biological residues.")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def select_hidden_state_embeddings(
|
| 54 |
+
last_hidden_state: Tensor,
|
| 55 |
+
hidden_states: tuple[Tensor, ...] | None,
|
| 56 |
+
*,
|
| 57 |
+
hidden_state_index: int = -1,
|
| 58 |
+
store_all_hidden_states: bool = False,
|
| 59 |
+
) -> Tensor:
|
| 60 |
+
"""Select one hidden state or stack every state without changing values."""
|
| 61 |
+
if store_all_hidden_states:
|
| 62 |
+
if not hidden_states:
|
| 63 |
+
raise ValueError("store_all_hidden_states requires model hidden states.")
|
| 64 |
+
# H has shape (b, n, l, d), where n follows the model's output order.
|
| 65 |
+
return torch.stack(hidden_states, dim=1)
|
| 66 |
+
if hidden_state_index == -1:
|
| 67 |
+
return last_hidden_state
|
| 68 |
+
if not hidden_states:
|
| 69 |
+
raise ValueError("hidden_state_index requires model hidden states.")
|
| 70 |
+
return hidden_states[hidden_state_index]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def iter_fasta(path: str | Path) -> Iterator[EmbeddingInput]:
|
| 74 |
+
"""Yield FASTA records in source order without reading the file into memory."""
|
| 75 |
+
|
| 76 |
+
identifier: str | None = None
|
| 77 |
+
sequence_parts: list[str] = []
|
| 78 |
+
found_record = False
|
| 79 |
+
with Path(path).open("r", encoding="utf-8") as handle:
|
| 80 |
+
for line_number, raw_line in enumerate(handle, start=1):
|
| 81 |
+
line = raw_line.strip()
|
| 82 |
+
if not line:
|
| 83 |
+
continue
|
| 84 |
+
if line.startswith(">"):
|
| 85 |
+
if identifier is not None:
|
| 86 |
+
found_record = True
|
| 87 |
+
yield EmbeddingInput(identifier, "".join(sequence_parts))
|
| 88 |
+
identifier = line[1:].strip().split(maxsplit=1)[0]
|
| 89 |
+
if not identifier:
|
| 90 |
+
raise ValueError(f"Missing FASTA identifier on line {line_number}.")
|
| 91 |
+
sequence_parts = []
|
| 92 |
+
else:
|
| 93 |
+
if identifier is None:
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"Sequence data precedes the first FASTA header on line {line_number}."
|
| 96 |
+
)
|
| 97 |
+
sequence_parts.append("".join(line.split()))
|
| 98 |
+
if identifier is not None:
|
| 99 |
+
found_record = True
|
| 100 |
+
yield EmbeddingInput(identifier, "".join(sequence_parts))
|
| 101 |
+
if not found_record:
|
| 102 |
+
raise ValueError(f"No FASTA records found in {path}.")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def parse_fasta(path: str | Path) -> list[EmbeddingInput]:
|
| 106 |
+
"""Parse FASTA records while preserving identifiers, order, and duplicates."""
|
| 107 |
+
|
| 108 |
+
return list(iter_fasta(path))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _normalize_input_item(
|
| 112 |
+
position: int,
|
| 113 |
+
item: str | EmbeddingInput | tuple[str, str],
|
| 114 |
+
) -> EmbeddingInput:
|
| 115 |
+
if isinstance(item, EmbeddingInput):
|
| 116 |
+
return item
|
| 117 |
+
if isinstance(item, str):
|
| 118 |
+
return EmbeddingInput(str(position), item)
|
| 119 |
+
if isinstance(item, tuple) and len(item) == 2:
|
| 120 |
+
return EmbeddingInput(str(item[0]), str(item[1]))
|
| 121 |
+
raise TypeError(
|
| 122 |
+
"inputs must contain sequences, EmbeddingInput values, or (id, sequence) tuples."
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class _InputSpool(Sequence[EmbeddingInput]):
|
| 127 |
+
"""Immutable disk-backed normalized inputs with an incremental digest."""
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
values: Iterable[str | EmbeddingInput | tuple[str, str]],
|
| 132 |
+
) -> None:
|
| 133 |
+
self._temporary: tempfile.TemporaryDirectory[str] | None = tempfile.TemporaryDirectory(
|
| 134 |
+
prefix="fastplms-inputs-"
|
| 135 |
+
)
|
| 136 |
+
self.path = Path(self._temporary.name) / "inputs.sqlite"
|
| 137 |
+
self._connection: sqlite3.Connection | None = sqlite3.connect(self.path)
|
| 138 |
+
self._connection.execute(
|
| 139 |
+
"CREATE TABLE inputs ("
|
| 140 |
+
"position INTEGER PRIMARY KEY, input_id TEXT NOT NULL, sequence TEXT NOT NULL)"
|
| 141 |
+
)
|
| 142 |
+
digest = hashlib.sha256()
|
| 143 |
+
count = 0
|
| 144 |
+
pending: list[tuple[int, str, str]] = []
|
| 145 |
+
try:
|
| 146 |
+
for position, item in enumerate(values):
|
| 147 |
+
record = _normalize_input_item(position, item)
|
| 148 |
+
for value in (record.id, record.sequence):
|
| 149 |
+
encoded = value.encode("utf-8")
|
| 150 |
+
digest.update(len(encoded).to_bytes(8, "big"))
|
| 151 |
+
digest.update(encoded)
|
| 152 |
+
pending.append((position, record.id, record.sequence))
|
| 153 |
+
count += 1
|
| 154 |
+
if len(pending) == 1_024:
|
| 155 |
+
self._connection.executemany("INSERT INTO inputs VALUES (?, ?, ?)", pending)
|
| 156 |
+
pending.clear()
|
| 157 |
+
if pending:
|
| 158 |
+
self._connection.executemany("INSERT INTO inputs VALUES (?, ?, ?)", pending)
|
| 159 |
+
if count == 0:
|
| 160 |
+
raise ValueError("inputs must contain at least one sequence.")
|
| 161 |
+
self._connection.commit()
|
| 162 |
+
self._connection.close()
|
| 163 |
+
self._connection = sqlite3.connect(
|
| 164 |
+
f"{self.path.resolve().as_uri()}?mode=ro",
|
| 165 |
+
uri=True,
|
| 166 |
+
)
|
| 167 |
+
except BaseException:
|
| 168 |
+
self.close()
|
| 169 |
+
raise
|
| 170 |
+
digest.update(count.to_bytes(8, "big"))
|
| 171 |
+
self.input_fingerprint = digest.hexdigest()
|
| 172 |
+
self._count = count
|
| 173 |
+
|
| 174 |
+
def _require_connection(self) -> sqlite3.Connection:
|
| 175 |
+
if self._connection is None:
|
| 176 |
+
raise RuntimeError("Input spool is closed.")
|
| 177 |
+
return self._connection
|
| 178 |
+
|
| 179 |
+
def __len__(self) -> int:
|
| 180 |
+
return self._count
|
| 181 |
+
|
| 182 |
+
def __iter__(self) -> Iterator[EmbeddingInput]:
|
| 183 |
+
cursor = self._require_connection().execute(
|
| 184 |
+
"SELECT input_id, sequence FROM inputs ORDER BY position"
|
| 185 |
+
)
|
| 186 |
+
while rows := cursor.fetchmany(1_024):
|
| 187 |
+
for input_id, sequence in rows:
|
| 188 |
+
yield EmbeddingInput(input_id, sequence)
|
| 189 |
+
|
| 190 |
+
@overload
|
| 191 |
+
def __getitem__(self, index: int, /) -> EmbeddingInput: ...
|
| 192 |
+
|
| 193 |
+
@overload
|
| 194 |
+
def __getitem__(self, index: slice, /) -> list[EmbeddingInput]: ...
|
| 195 |
+
|
| 196 |
+
def __getitem__(self, index: int | slice) -> EmbeddingInput | list[EmbeddingInput]:
|
| 197 |
+
connection = self._require_connection()
|
| 198 |
+
|
| 199 |
+
if isinstance(index, slice):
|
| 200 |
+
start, stop, step = index.indices(self._count)
|
| 201 |
+
if step != 1:
|
| 202 |
+
return [self[position] for position in range(start, stop, step)]
|
| 203 |
+
rows = connection.execute(
|
| 204 |
+
"SELECT input_id, sequence FROM inputs "
|
| 205 |
+
"WHERE position >= ? AND position < ? ORDER BY position",
|
| 206 |
+
(start, stop),
|
| 207 |
+
).fetchall()
|
| 208 |
+
return [EmbeddingInput(input_id, sequence) for input_id, sequence in rows]
|
| 209 |
+
position = index + self._count if index < 0 else index
|
| 210 |
+
if position < 0 or position >= self._count:
|
| 211 |
+
raise IndexError(index)
|
| 212 |
+
row = connection.execute(
|
| 213 |
+
"SELECT input_id, sequence FROM inputs WHERE position = ?", (position,)
|
| 214 |
+
).fetchone()
|
| 215 |
+
if row is None:
|
| 216 |
+
raise IndexError(index)
|
| 217 |
+
return EmbeddingInput(row[0], row[1])
|
| 218 |
+
|
| 219 |
+
def close(self) -> None:
|
| 220 |
+
connection = getattr(self, "_connection", None)
|
| 221 |
+
if connection is not None:
|
| 222 |
+
connection.close()
|
| 223 |
+
self._connection = None
|
| 224 |
+
temporary = getattr(self, "_temporary", None)
|
| 225 |
+
if temporary is not None:
|
| 226 |
+
temporary.cleanup()
|
| 227 |
+
self._temporary = None
|
| 228 |
+
|
| 229 |
+
def __del__(self) -> None:
|
| 230 |
+
self.close()
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _normalize_inputs(
|
| 234 |
+
inputs: (Iterable[str | EmbeddingInput | tuple[str, str]] | Mapping[str, str] | str | Path),
|
| 235 |
+
*,
|
| 236 |
+
disk_backed: bool,
|
| 237 |
+
) -> Sequence[EmbeddingInput]:
|
| 238 |
+
is_fasta_path = isinstance(inputs, Path)
|
| 239 |
+
if isinstance(inputs, str):
|
| 240 |
+
try:
|
| 241 |
+
is_fasta_path = Path(inputs).is_file()
|
| 242 |
+
except OSError:
|
| 243 |
+
is_fasta_path = False
|
| 244 |
+
should_spool = disk_backed or is_fasta_path or not isinstance(inputs, (str, Sequence, Mapping))
|
| 245 |
+
values: Iterable[str | EmbeddingInput | tuple[str, str]]
|
| 246 |
+
if isinstance(inputs, Path):
|
| 247 |
+
values = iter_fasta(inputs)
|
| 248 |
+
elif isinstance(inputs, str):
|
| 249 |
+
values = iter_fasta(inputs) if is_fasta_path else [inputs]
|
| 250 |
+
elif isinstance(inputs, Mapping):
|
| 251 |
+
values = inputs.items()
|
| 252 |
+
else:
|
| 253 |
+
values = inputs
|
| 254 |
+
if should_spool:
|
| 255 |
+
return _InputSpool(values)
|
| 256 |
+
records: list[EmbeddingInput] = []
|
| 257 |
+
for position, item in enumerate(values):
|
| 258 |
+
records.append(_normalize_input_item(position, item))
|
| 259 |
+
if not records:
|
| 260 |
+
raise ValueError("inputs must contain at least one sequence.")
|
| 261 |
+
return records
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _validate_untruncated_lengths(
|
| 265 |
+
records: Sequence[EmbeddingInput],
|
| 266 |
+
*,
|
| 267 |
+
max_length: int | None,
|
| 268 |
+
truncate: bool,
|
| 269 |
+
) -> None:
|
| 270 |
+
"""Fail before inference when a biological-residue limit would be exceeded."""
|
| 271 |
+
|
| 272 |
+
if max_length is None or truncate:
|
| 273 |
+
return
|
| 274 |
+
for position, record in enumerate(records):
|
| 275 |
+
residue_count = len(record.sequence)
|
| 276 |
+
if residue_count > max_length:
|
| 277 |
+
raise ValueError(
|
| 278 |
+
f"Input at position {position} with id {record.id!r} has "
|
| 279 |
+
f"{residue_count} biological residues, exceeding max_length={max_length} "
|
| 280 |
+
"while truncate=False."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _model_device(model: Any) -> torch.device:
|
| 285 |
+
try:
|
| 286 |
+
return torch.device(next(model.parameters()).device)
|
| 287 |
+
except (AttributeError, StopIteration):
|
| 288 |
+
return torch.device("cpu")
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _attention_backend(model: Any) -> str | None:
|
| 292 |
+
config = getattr(model, "config", None)
|
| 293 |
+
for name in ("_attn_implementation", "attn_implementation", "attn_backend"):
|
| 294 |
+
value = getattr(config, name, None)
|
| 295 |
+
if value:
|
| 296 |
+
return str(value)
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _attention_kernel_metadata(backend: str | None) -> dict[str, Any] | None:
|
| 301 |
+
if backend not in {"flash_attention_2", "flash_attention_3"}:
|
| 302 |
+
return None
|
| 303 |
+
from fastplms.registry import get_model_registry
|
| 304 |
+
|
| 305 |
+
spec = get_model_registry().attention_kernels[backend]
|
| 306 |
+
return {
|
| 307 |
+
"repository": spec.repository,
|
| 308 |
+
"revision": spec.revision,
|
| 309 |
+
"version": spec.version,
|
| 310 |
+
"expected_variant": spec.expected_variant,
|
| 311 |
+
"dtypes": list(spec.dtypes),
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _fingerprint_jsonable(value: Any) -> Any:
|
| 316 |
+
if isinstance(value, Mapping):
|
| 317 |
+
return {str(key): _fingerprint_jsonable(item) for key, item in value.items()}
|
| 318 |
+
if isinstance(value, (list, tuple)):
|
| 319 |
+
return [_fingerprint_jsonable(item) for item in value]
|
| 320 |
+
if isinstance(value, (set, frozenset)):
|
| 321 |
+
return sorted((_fingerprint_jsonable(item) for item in value), key=repr)
|
| 322 |
+
if isinstance(value, Path):
|
| 323 |
+
return str(value)
|
| 324 |
+
if isinstance(value, Tensor):
|
| 325 |
+
return {
|
| 326 |
+
"dtype": str(value.dtype).removeprefix("torch."),
|
| 327 |
+
"shape": list(value.shape),
|
| 328 |
+
"sha256": tensor_sha256(value),
|
| 329 |
+
}
|
| 330 |
+
if isinstance(value, torch.dtype):
|
| 331 |
+
return str(value).removeprefix("torch.")
|
| 332 |
+
if isinstance(value, torch.device):
|
| 333 |
+
return str(value)
|
| 334 |
+
if value is None or isinstance(value, (str, int, float, bool)):
|
| 335 |
+
return value
|
| 336 |
+
return {
|
| 337 |
+
"class": f"{value.__class__.__module__}.{value.__class__.__qualname__}",
|
| 338 |
+
"value": str(value),
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _tokenizer_content_sha256(tokenizer: Any) -> str:
|
| 343 |
+
content: dict[str, Any] = {
|
| 344 |
+
"init_kwargs": getattr(tokenizer, "init_kwargs", None),
|
| 345 |
+
"special_tokens_map": getattr(tokenizer, "special_tokens_map", None),
|
| 346 |
+
"model_max_length": getattr(tokenizer, "model_max_length", None),
|
| 347 |
+
"padding_side": getattr(tokenizer, "padding_side", None),
|
| 348 |
+
"truncation_side": getattr(tokenizer, "truncation_side", None),
|
| 349 |
+
}
|
| 350 |
+
get_vocab = getattr(tokenizer, "get_vocab", None)
|
| 351 |
+
if callable(get_vocab):
|
| 352 |
+
content["vocabulary"] = get_vocab()
|
| 353 |
+
get_added_vocab = getattr(tokenizer, "get_added_vocab", None)
|
| 354 |
+
if callable(get_added_vocab):
|
| 355 |
+
content["added_vocabulary"] = get_added_vocab()
|
| 356 |
+
backend = getattr(tokenizer, "backend_tokenizer", None)
|
| 357 |
+
backend_to_str = getattr(backend, "to_str", None)
|
| 358 |
+
if callable(backend_to_str):
|
| 359 |
+
content["backend"] = backend_to_str()
|
| 360 |
+
serialized = json.dumps(
|
| 361 |
+
_fingerprint_jsonable(content),
|
| 362 |
+
sort_keys=True,
|
| 363 |
+
separators=(",", ":"),
|
| 364 |
+
ensure_ascii=False,
|
| 365 |
+
).encode()
|
| 366 |
+
return hashlib.sha256(serialized).hexdigest()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _tokenizer_metadata(model: Any, tokenizer: Any | None) -> dict[str, Any]:
|
| 370 |
+
resolved = tokenizer if tokenizer is not None else getattr(model, "tokenizer", None)
|
| 371 |
+
if resolved is None:
|
| 372 |
+
# Raw-sequence families such as E1 retain their loader context on the
|
| 373 |
+
# model/encoder rather than exposing a Transformers tokenizer. Bind the
|
| 374 |
+
# non-secret source policy to resume identity without serializing a Hub
|
| 375 |
+
# token or forcing lazy tokenizer initialization.
|
| 376 |
+
for candidate in (model, getattr(model, "model", None)):
|
| 377 |
+
settings = getattr(candidate, "__dict__", {}).get("_fastplms_tokenizer_kwargs")
|
| 378 |
+
if isinstance(settings, Mapping):
|
| 379 |
+
token_value = settings.get("token")
|
| 380 |
+
return {
|
| 381 |
+
"mode": "native-sequence",
|
| 382 |
+
"source": (
|
| 383 |
+
str(settings.get("tokenizer_source"))
|
| 384 |
+
if settings.get("tokenizer_source") is not None
|
| 385 |
+
else None
|
| 386 |
+
),
|
| 387 |
+
"revision": settings.get("revision"),
|
| 388 |
+
"cache_dir": (
|
| 389 |
+
str(settings.get("cache_dir"))
|
| 390 |
+
if settings.get("cache_dir") is not None
|
| 391 |
+
else None
|
| 392 |
+
),
|
| 393 |
+
"local_files_only": bool(settings.get("local_files_only", False)),
|
| 394 |
+
"token_policy": (
|
| 395 |
+
"disabled"
|
| 396 |
+
if token_value is False
|
| 397 |
+
else "provided"
|
| 398 |
+
if token_value is not None
|
| 399 |
+
else "default"
|
| 400 |
+
),
|
| 401 |
+
}
|
| 402 |
+
return {"mode": "native-sequence"}
|
| 403 |
+
return {
|
| 404 |
+
"mode": "tokenizer",
|
| 405 |
+
"class": f"{resolved.__class__.__module__}.{resolved.__class__.__qualname__}",
|
| 406 |
+
"name_or_path": getattr(resolved, "name_or_path", None),
|
| 407 |
+
"vocab_size": getattr(resolved, "vocab_size", None),
|
| 408 |
+
"special_token_ids": list(getattr(resolved, "all_special_ids", ())),
|
| 409 |
+
"content_sha256": _tokenizer_content_sha256(resolved),
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@contextmanager
|
| 414 |
+
def _temporary_eval(model: Any) -> Iterator[None]:
|
| 415 |
+
was_training = getattr(model, "training", None)
|
| 416 |
+
eval_method = getattr(model, "eval", None)
|
| 417 |
+
train_method = getattr(model, "train", None)
|
| 418 |
+
if (
|
| 419 |
+
not isinstance(was_training, bool)
|
| 420 |
+
or not callable(eval_method)
|
| 421 |
+
or not callable(train_method)
|
| 422 |
+
):
|
| 423 |
+
yield
|
| 424 |
+
return
|
| 425 |
+
eval_method()
|
| 426 |
+
try:
|
| 427 |
+
yield
|
| 428 |
+
finally:
|
| 429 |
+
train_method(was_training)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def _software_versions() -> dict[str, str | None]:
|
| 433 |
+
try:
|
| 434 |
+
import fastplms
|
| 435 |
+
|
| 436 |
+
fastplms_version = fastplms.__version__
|
| 437 |
+
except (AttributeError, ImportError):
|
| 438 |
+
fastplms_version = None
|
| 439 |
+
try:
|
| 440 |
+
import safetensors
|
| 441 |
+
|
| 442 |
+
safetensors_version = safetensors.__version__
|
| 443 |
+
except ImportError:
|
| 444 |
+
safetensors_version = None
|
| 445 |
+
try:
|
| 446 |
+
import transformers
|
| 447 |
+
|
| 448 |
+
transformers_version = transformers.__version__
|
| 449 |
+
except ImportError:
|
| 450 |
+
transformers_version = None
|
| 451 |
+
return {
|
| 452 |
+
"fastplms": fastplms_version,
|
| 453 |
+
"python": platform.python_version(),
|
| 454 |
+
"safetensors": safetensors_version,
|
| 455 |
+
"torch": torch.__version__,
|
| 456 |
+
"torch_cuda": torch.version.cuda,
|
| 457 |
+
"transformers": transformers_version,
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def _adapter_identity_metadata(model: Any) -> dict[str, Any] | None:
|
| 462 |
+
"""Return deterministic PEFT/adapter identity without tensor payloads."""
|
| 463 |
+
|
| 464 |
+
peft_config = getattr(model, "peft_config", None)
|
| 465 |
+
if not isinstance(peft_config, Mapping) or not peft_config:
|
| 466 |
+
return None
|
| 467 |
+
configurations: dict[str, Any] = {}
|
| 468 |
+
for name, config in sorted(peft_config.items(), key=lambda item: str(item[0])):
|
| 469 |
+
to_dict = getattr(config, "to_dict", None)
|
| 470 |
+
if callable(to_dict):
|
| 471 |
+
value = to_dict()
|
| 472 |
+
else:
|
| 473 |
+
try:
|
| 474 |
+
value = vars(config)
|
| 475 |
+
except TypeError:
|
| 476 |
+
value = config
|
| 477 |
+
configurations[str(name)] = _fingerprint_jsonable(value)
|
| 478 |
+
active_adapters = getattr(model, "active_adapters", None)
|
| 479 |
+
if callable(active_adapters):
|
| 480 |
+
active_adapters = active_adapters()
|
| 481 |
+
return {
|
| 482 |
+
"active": _fingerprint_jsonable(active_adapters),
|
| 483 |
+
"configurations": configurations,
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _execution_identity_metadata(model: Any) -> dict[str, Any]:
|
| 488 |
+
"""Capture runtime policy that can change persisted numerical results."""
|
| 489 |
+
|
| 490 |
+
parameter_dtypes = sorted(
|
| 491 |
+
{
|
| 492 |
+
str(parameter.dtype).removeprefix("torch.")
|
| 493 |
+
for parameter in getattr(model, "parameters", lambda: ())()
|
| 494 |
+
}
|
| 495 |
+
)
|
| 496 |
+
return {
|
| 497 |
+
"device": _model_device(model).type,
|
| 498 |
+
"hf_device_map": _fingerprint_jsonable(getattr(model, "hf_device_map", None)),
|
| 499 |
+
"parameter_dtypes": parameter_dtypes,
|
| 500 |
+
"software": _software_versions(),
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _biological_residue_mask(
|
| 505 |
+
input_ids: Tensor,
|
| 506 |
+
attention_mask: Tensor,
|
| 507 |
+
tokenizer: Any,
|
| 508 |
+
) -> Tensor:
|
| 509 |
+
"""Remove padding and tokenizer-declared special tokens from M."""
|
| 510 |
+
|
| 511 |
+
M = attention_mask.to(dtype=torch.bool)
|
| 512 |
+
special_ids = tuple(int(token_id) for token_id in getattr(tokenizer, "all_special_ids", ()))
|
| 513 |
+
if special_ids:
|
| 514 |
+
specials = torch.tensor(special_ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 515 |
+
M = M & ~torch.isin(input_ids, specials)
|
| 516 |
+
return M
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _generic_embedding_batch(
|
| 520 |
+
model: Any,
|
| 521 |
+
sequences: list[str],
|
| 522 |
+
*,
|
| 523 |
+
tokenizer: Any | None,
|
| 524 |
+
max_length: int | None,
|
| 525 |
+
truncate: bool,
|
| 526 |
+
need_attentions: bool,
|
| 527 |
+
model_kwargs: dict[str, Any],
|
| 528 |
+
) -> EmbeddingBatch:
|
| 529 |
+
config = getattr(model, "config", None)
|
| 530 |
+
model_type = str(getattr(config, "model_type", "")).lower()
|
| 531 |
+
if tokenizer is None:
|
| 532 |
+
tokenizer = getattr(model, "tokenizer", None)
|
| 533 |
+
|
| 534 |
+
if tokenizer is None and model_type == "e1":
|
| 535 |
+
output = model._embed(sequences, return_attention_mask=True, **model_kwargs)
|
| 536 |
+
if not isinstance(output, tuple) or len(output) != 2:
|
| 537 |
+
raise TypeError("E1 _embed must return (X, residue_mask).")
|
| 538 |
+
X, M = output
|
| 539 |
+
preparer = getattr(model, "prep_tokens", None)
|
| 540 |
+
if preparer is not None and hasattr(preparer, "get_batch_kwargs"):
|
| 541 |
+
prepared = preparer.get_batch_kwargs(sequences, device=X.device)
|
| 542 |
+
input_ids = prepared["input_ids"]
|
| 543 |
+
boundary_ids = preparer.boundary_token_ids.to(
|
| 544 |
+
device=input_ids.device, dtype=input_ids.dtype
|
| 545 |
+
)
|
| 546 |
+
# E1 wraps each raw sequence in BOS, context-label, terminal-label,
|
| 547 |
+
# and EOS tokens. Only amino-acid rows are biological residues.
|
| 548 |
+
M = M.to(dtype=torch.bool) & ~torch.isin(input_ids, boundary_ids)
|
| 549 |
+
if need_attentions:
|
| 550 |
+
raise ValueError("parti is not available for tokenizer-free E1 embedding.")
|
| 551 |
+
return EmbeddingBatch(X=X, residue_mask=M.to(dtype=torch.bool))
|
| 552 |
+
if tokenizer is None:
|
| 553 |
+
raise ValueError("A tokenizer is required for this model's embedding path.")
|
| 554 |
+
|
| 555 |
+
tokenize_kwargs: dict[str, Any] = {
|
| 556 |
+
"return_tensors": "pt",
|
| 557 |
+
"padding": True,
|
| 558 |
+
"truncation": truncate,
|
| 559 |
+
}
|
| 560 |
+
if max_length is not None and truncate:
|
| 561 |
+
# ``max_length`` is a biological-residue limit. Tokenizer limits include
|
| 562 |
+
# boundary tokens, so reserve their declared width instead of dropping
|
| 563 |
+
# residues at the exact boundary.
|
| 564 |
+
special_token_count = 0
|
| 565 |
+
num_special_tokens_to_add = getattr(tokenizer, "num_special_tokens_to_add", None)
|
| 566 |
+
if callable(num_special_tokens_to_add):
|
| 567 |
+
special_token_count = int(num_special_tokens_to_add(pair=False))
|
| 568 |
+
tokenize_kwargs["max_length"] = max_length + special_token_count
|
| 569 |
+
sequence_tokenizer = getattr(model, "_tokenize_sequence_batch", None)
|
| 570 |
+
if callable(sequence_tokenizer):
|
| 571 |
+
encoded = sequence_tokenizer(sequences, tokenizer=tokenizer, **tokenize_kwargs)
|
| 572 |
+
else:
|
| 573 |
+
encoded = tokenizer(sequences, **tokenize_kwargs)
|
| 574 |
+
device = _model_device(model)
|
| 575 |
+
input_ids = encoded["input_ids"].to(device)
|
| 576 |
+
attention_mask = encoded.get("attention_mask", input_ids.new_ones(input_ids.shape)).to(device)
|
| 577 |
+
M = _biological_residue_mask(input_ids, attention_mask, tokenizer)
|
| 578 |
+
if need_attentions:
|
| 579 |
+
# Validate l before either the backbone or its quadratic attention graph
|
| 580 |
+
# is materialized. M has shape (b, l).
|
| 581 |
+
_validate_parti_length(M)
|
| 582 |
+
X = model._embed(input_ids, attention_mask, **model_kwargs)
|
| 583 |
+
attentions = None
|
| 584 |
+
if need_attentions:
|
| 585 |
+
output = model(
|
| 586 |
+
input_ids=input_ids,
|
| 587 |
+
attention_mask=attention_mask,
|
| 588 |
+
output_attentions=True,
|
| 589 |
+
return_dict=True,
|
| 590 |
+
)
|
| 591 |
+
attentions = getattr(output, "attentions", None)
|
| 592 |
+
if attentions is None:
|
| 593 |
+
raise ValueError("The model did not return attentions required by parti.")
|
| 594 |
+
return EmbeddingBatch(X=X, residue_mask=M, attentions=attentions)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _first_metadata_value(*values: Any) -> Any:
|
| 598 |
+
for value in values:
|
| 599 |
+
if isinstance(value, str):
|
| 600 |
+
if value.strip():
|
| 601 |
+
return value
|
| 602 |
+
elif value is not None:
|
| 603 |
+
return value
|
| 604 |
+
return None
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def _model_identity_metadata(model: Any) -> dict[str, Any]:
|
| 608 |
+
"""Resolve model and checkpoint identity, including local artifact fallbacks."""
|
| 609 |
+
|
| 610 |
+
config = getattr(model, "config", None)
|
| 611 |
+
checkpoint_revision = _first_metadata_value(
|
| 612 |
+
getattr(config, "fastplms_checkpoint_revision", None),
|
| 613 |
+
getattr(config, "_commit_hash", None),
|
| 614 |
+
)
|
| 615 |
+
return {
|
| 616 |
+
"model_id": _first_metadata_value(
|
| 617 |
+
getattr(config, "fastplms_model_id", None),
|
| 618 |
+
getattr(config, "_name_or_path", None),
|
| 619 |
+
),
|
| 620 |
+
"model_revision": _first_metadata_value(
|
| 621 |
+
getattr(config, "_commit_hash", None),
|
| 622 |
+
checkpoint_revision,
|
| 623 |
+
),
|
| 624 |
+
"checkpoint_repo_id": getattr(config, "fastplms_checkpoint_repo_id", None),
|
| 625 |
+
"checkpoint_revision": checkpoint_revision,
|
| 626 |
+
"checkpoint_hash": _first_metadata_value(
|
| 627 |
+
getattr(model, "checkpoint_hash", None),
|
| 628 |
+
getattr(config, "checkpoint_hash", None),
|
| 629 |
+
getattr(config, "fastplms_checkpoint_hash", None),
|
| 630 |
+
),
|
| 631 |
+
"weights_revision": getattr(config, "fastplms_weights_revision", None),
|
| 632 |
+
"runtime_revision": getattr(config, "fastplms_runtime_revision", None),
|
| 633 |
+
"source_tree_sha256": getattr(config, "fastplms_source_tree_sha256", None),
|
| 634 |
+
"runtime_bundle_sha256": getattr(config, "fastplms_runtime_bundle_sha256", None),
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def _bounded_tensor_chunks(X: Tensor, max_elements: int) -> Iterable[Tensor]:
|
| 639 |
+
"""Yield X in logical row-major order without materializing a full copy."""
|
| 640 |
+
|
| 641 |
+
if X.numel() == 0:
|
| 642 |
+
return
|
| 643 |
+
if X.ndim == 0:
|
| 644 |
+
yield X
|
| 645 |
+
return
|
| 646 |
+
trailing_elements = 1
|
| 647 |
+
for size in X.shape[1:]:
|
| 648 |
+
trailing_elements *= int(size)
|
| 649 |
+
if trailing_elements <= max_elements:
|
| 650 |
+
rows_per_chunk = max(1, max_elements // trailing_elements)
|
| 651 |
+
for start in range(0, X.shape[0], rows_per_chunk):
|
| 652 |
+
yield X[start : start + rows_per_chunk]
|
| 653 |
+
return
|
| 654 |
+
for row in X:
|
| 655 |
+
yield from _bounded_tensor_chunks(row, max_elements)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def _model_state_sha256(model: Any) -> str:
|
| 659 |
+
"""Hash named parameters and persistent buffers using bounded CPU copies."""
|
| 660 |
+
|
| 661 |
+
# Never cache this digest from tensor identity or ``Tensor._version``.
|
| 662 |
+
# ``Parameter.data`` and independent tensor aliases can mutate shared storage
|
| 663 |
+
# without changing either signal, while persisted resume identity must bind
|
| 664 |
+
# the authoritative bytes visible at the start of this run.
|
| 665 |
+
state = model.state_dict(keep_vars=True)
|
| 666 |
+
digest = hashlib.sha256()
|
| 667 |
+
for name, value in sorted(state.items()):
|
| 668 |
+
if not isinstance(value, Tensor):
|
| 669 |
+
raise TypeError(f"Model state entry {name!r} is not a tensor.")
|
| 670 |
+
if value.is_meta:
|
| 671 |
+
raise ValueError(
|
| 672 |
+
f"Cannot fingerprint meta-device model state entry {name!r}; pass "
|
| 673 |
+
"model_state_fingerprint with a caller-owned state identity."
|
| 674 |
+
)
|
| 675 |
+
header = json.dumps(
|
| 676 |
+
{
|
| 677 |
+
"name": name,
|
| 678 |
+
"dtype": str(value.dtype).removeprefix("torch."),
|
| 679 |
+
"shape": list(value.shape),
|
| 680 |
+
},
|
| 681 |
+
sort_keys=True,
|
| 682 |
+
separators=(",", ":"),
|
| 683 |
+
).encode()
|
| 684 |
+
digest.update(len(header).to_bytes(8, "big"))
|
| 685 |
+
digest.update(header)
|
| 686 |
+
max_elements = max(1, _MODEL_STATE_HASH_CHUNK_BYTES // value.element_size())
|
| 687 |
+
for chunk in _bounded_tensor_chunks(value.detach(), max_elements):
|
| 688 |
+
cpu_chunk = chunk.to(device="cpu").contiguous()
|
| 689 |
+
digest.update(cpu_chunk.reshape(-1).view(torch.uint8).numpy().tobytes())
|
| 690 |
+
return digest.hexdigest()
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def _input_sha256(records: Iterable[EmbeddingInput]) -> str:
|
| 694 |
+
"""Hash an ordered input stream without constructing a duplicate JSON payload."""
|
| 695 |
+
|
| 696 |
+
precomputed = getattr(records, "input_fingerprint", None)
|
| 697 |
+
if isinstance(precomputed, str):
|
| 698 |
+
return precomputed
|
| 699 |
+
digest = hashlib.sha256()
|
| 700 |
+
count = 0
|
| 701 |
+
for record in records:
|
| 702 |
+
count += 1
|
| 703 |
+
for value in (record.id, record.sequence):
|
| 704 |
+
encoded = value.encode("utf-8")
|
| 705 |
+
digest.update(len(encoded).to_bytes(8, "big"))
|
| 706 |
+
digest.update(encoded)
|
| 707 |
+
digest.update(count.to_bytes(8, "big"))
|
| 708 |
+
return digest.hexdigest()
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def _run_fingerprint(
|
| 712 |
+
model: Any,
|
| 713 |
+
records: Sequence[EmbeddingInput],
|
| 714 |
+
*,
|
| 715 |
+
pooling: Sequence[str],
|
| 716 |
+
full_embeddings: bool,
|
| 717 |
+
max_length: int | None,
|
| 718 |
+
truncate: bool,
|
| 719 |
+
dtype: torch.dtype | None,
|
| 720 |
+
model_kwargs: dict[str, Any],
|
| 721 |
+
tokenizer_metadata: dict[str, Any],
|
| 722 |
+
model_state_fingerprint: str | None,
|
| 723 |
+
persist_output: bool,
|
| 724 |
+
embedding_context: Mapping[str, Any],
|
| 725 |
+
batch_size: int,
|
| 726 |
+
batch_window_size: int,
|
| 727 |
+
max_tokens_per_batch: int | None,
|
| 728 |
+
) -> tuple[str, str, str | None, str]:
|
| 729 |
+
input_fingerprint = _input_sha256(records)
|
| 730 |
+
attention_backend = _attention_backend(model)
|
| 731 |
+
model_identity = _model_identity_metadata(model)
|
| 732 |
+
if model_state_fingerprint is None and persist_output:
|
| 733 |
+
resolved_model_state_fingerprint = _model_state_sha256(model)
|
| 734 |
+
model_state_fingerprint_source = "computed"
|
| 735 |
+
elif model_state_fingerprint is not None:
|
| 736 |
+
resolved_model_state_fingerprint = model_state_fingerprint.strip()
|
| 737 |
+
if not resolved_model_state_fingerprint:
|
| 738 |
+
raise ValueError("model_state_fingerprint must not be empty.")
|
| 739 |
+
model_state_fingerprint_source = "caller"
|
| 740 |
+
else:
|
| 741 |
+
resolved_model_state_fingerprint = None
|
| 742 |
+
model_state_fingerprint_source = "not-computed"
|
| 743 |
+
payload = {
|
| 744 |
+
"fingerprint_schema_version": _RUN_FINGERPRINT_SCHEMA_VERSION,
|
| 745 |
+
"input_fingerprint": input_fingerprint,
|
| 746 |
+
"model_state_fingerprint": resolved_model_state_fingerprint,
|
| 747 |
+
"model_state_fingerprint_source": model_state_fingerprint_source,
|
| 748 |
+
"model_class": f"{model.__class__.__module__}.{model.__class__.__qualname__}",
|
| 749 |
+
**model_identity,
|
| 750 |
+
"attention_backend": attention_backend,
|
| 751 |
+
"attention_kernel": _attention_kernel_metadata(attention_backend),
|
| 752 |
+
"layer": repr(
|
| 753 |
+
getattr(model, "embedding_layer", model_kwargs.get("hidden_state_index", -1))
|
| 754 |
+
),
|
| 755 |
+
"projection": getattr(model, "embedding_projection", None),
|
| 756 |
+
"esmc_source": getattr(model, "_esmc_source", None),
|
| 757 |
+
"esmc_revision": getattr(model, "_esmc_source_revision", None),
|
| 758 |
+
"esmc_files": getattr(model, "_esmc_source_files", None),
|
| 759 |
+
"token_policy": getattr(model, "embedding_token_policy", None),
|
| 760 |
+
"tokenizer": tokenizer_metadata,
|
| 761 |
+
"adapter": _adapter_identity_metadata(model),
|
| 762 |
+
"execution": _execution_identity_metadata(model),
|
| 763 |
+
"embedding_context": _fingerprint_jsonable(embedding_context),
|
| 764 |
+
"pooling": list(pooling),
|
| 765 |
+
"full_embeddings": full_embeddings,
|
| 766 |
+
"max_length": max_length,
|
| 767 |
+
"truncate": truncate,
|
| 768 |
+
"dtype": str(dtype) if dtype is not None else None,
|
| 769 |
+
"batching": {
|
| 770 |
+
"batch_size": batch_size,
|
| 771 |
+
"batch_window_size": batch_window_size,
|
| 772 |
+
"max_tokens_per_batch": max_tokens_per_batch,
|
| 773 |
+
"input_storage": ("disk-spool" if isinstance(records, _InputSpool) else "memory"),
|
| 774 |
+
},
|
| 775 |
+
"model_kwargs": {
|
| 776 |
+
key: _fingerprint_jsonable(value) for key, value in sorted(model_kwargs.items())
|
| 777 |
+
},
|
| 778 |
+
"residue_mask_policy": "attention-mask-minus-special-tokens",
|
| 779 |
+
}
|
| 780 |
+
run_fingerprint = hashlib.sha256(
|
| 781 |
+
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
|
| 782 |
+
).hexdigest()
|
| 783 |
+
return (
|
| 784 |
+
input_fingerprint,
|
| 785 |
+
run_fingerprint,
|
| 786 |
+
resolved_model_state_fingerprint,
|
| 787 |
+
model_state_fingerprint_source,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _output_exists(path: str | Path, format: str) -> bool:
|
| 792 |
+
path = Path(path)
|
| 793 |
+
if format == "sqlite":
|
| 794 |
+
return path.is_file()
|
| 795 |
+
return safetensors_result_exists(path)
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
def _output_descriptor(position: int, record: EmbeddingRecord) -> dict[str, Any]:
|
| 799 |
+
tensor = record.tensor
|
| 800 |
+
if isinstance(tensor, LazyTensorReference):
|
| 801 |
+
dtype = tensor.dtype
|
| 802 |
+
shape = tensor.shape
|
| 803 |
+
digest = tensor.sha256
|
| 804 |
+
else:
|
| 805 |
+
dtype = str(tensor.dtype).removeprefix("torch.")
|
| 806 |
+
shape = tuple(tensor.shape)
|
| 807 |
+
digest = tensor_sha256(tensor)
|
| 808 |
+
return {
|
| 809 |
+
"position": position,
|
| 810 |
+
"id": record.id,
|
| 811 |
+
"dtype": dtype,
|
| 812 |
+
"shape": shape,
|
| 813 |
+
"sha256": digest,
|
| 814 |
+
}
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def _ordered_string_sha256(values: Sequence[str]) -> str:
|
| 818 |
+
digest = hashlib.sha256()
|
| 819 |
+
for value in values:
|
| 820 |
+
encoded = value.encode("utf-8")
|
| 821 |
+
digest.update(len(encoded).to_bytes(8, "big"))
|
| 822 |
+
digest.update(encoded)
|
| 823 |
+
digest.update(len(values).to_bytes(8, "big"))
|
| 824 |
+
return digest.hexdigest()
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def _embedding_context(
|
| 828 |
+
model: Any,
|
| 829 |
+
records: Sequence[EmbeddingInput],
|
| 830 |
+
*,
|
| 831 |
+
hidden_state_source: str,
|
| 832 |
+
decoder_inputs: Sequence[str] | None,
|
| 833 |
+
decoder_input_ids: Tensor | None,
|
| 834 |
+
decoder_attention_mask: Tensor | None,
|
| 835 |
+
model_kwargs: Mapping[str, Any],
|
| 836 |
+
) -> tuple[dict[str, Any], tuple[str, ...] | None]:
|
| 837 |
+
if hidden_state_source not in {"encoder", "decoder"}:
|
| 838 |
+
raise ValueError("hidden_state_source must be 'encoder' or 'decoder'.")
|
| 839 |
+
hidden_state_index = model_kwargs.get("hidden_state_index", -1)
|
| 840 |
+
if not isinstance(hidden_state_index, int) or isinstance(hidden_state_index, bool):
|
| 841 |
+
raise TypeError("hidden_state_index must be an integer.")
|
| 842 |
+
store_all_hidden_states = model_kwargs.get("store_all_hidden_states", False)
|
| 843 |
+
if not isinstance(store_all_hidden_states, bool):
|
| 844 |
+
raise TypeError("store_all_hidden_states must be a boolean.")
|
| 845 |
+
normalized_decoder_inputs: tuple[str, ...] | None = None
|
| 846 |
+
has_decoder_inputs = decoder_inputs is not None
|
| 847 |
+
has_decoder_ids = decoder_input_ids is not None
|
| 848 |
+
if hidden_state_source == "encoder":
|
| 849 |
+
if has_decoder_inputs or has_decoder_ids or decoder_attention_mask is not None:
|
| 850 |
+
raise ValueError("Decoder inputs are only valid when hidden_state_source='decoder'.")
|
| 851 |
+
else:
|
| 852 |
+
if has_decoder_inputs == has_decoder_ids:
|
| 853 |
+
raise ValueError(
|
| 854 |
+
"Decoder embedding requires exactly one of decoder_inputs or decoder_input_ids."
|
| 855 |
+
)
|
| 856 |
+
decoder_input_fingerprint: str | None = None
|
| 857 |
+
if decoder_inputs is not None:
|
| 858 |
+
if isinstance(decoder_inputs, (str, bytes)) or not isinstance(decoder_inputs, Sequence):
|
| 859 |
+
raise TypeError("decoder_inputs must be an aligned sequence of strings.")
|
| 860 |
+
normalized_decoder_inputs = tuple(decoder_inputs)
|
| 861 |
+
if not all(isinstance(value, str) and value for value in normalized_decoder_inputs):
|
| 862 |
+
raise ValueError("decoder_inputs must contain non-empty strings.")
|
| 863 |
+
if len(normalized_decoder_inputs) != len(records):
|
| 864 |
+
raise ValueError("decoder_inputs must align one-to-one with embedding inputs.")
|
| 865 |
+
decoder_input_fingerprint = _ordered_string_sha256(normalized_decoder_inputs)
|
| 866 |
+
if decoder_attention_mask is not None:
|
| 867 |
+
raise ValueError("decoder_attention_mask requires decoder_input_ids.")
|
| 868 |
+
if decoder_input_ids is not None:
|
| 869 |
+
if not isinstance(decoder_input_ids, Tensor) or decoder_input_ids.ndim != 2:
|
| 870 |
+
raise ValueError("decoder_input_ids must have shape (batch, sequence).")
|
| 871 |
+
if decoder_input_ids.shape[0] != len(records):
|
| 872 |
+
raise ValueError("decoder_input_ids must align one-to-one with embedding inputs.")
|
| 873 |
+
if decoder_input_ids.dtype == torch.bool or decoder_input_ids.is_floating_point():
|
| 874 |
+
raise TypeError("decoder_input_ids must use an integer token dtype.")
|
| 875 |
+
decoder_input_fingerprint = tensor_sha256(decoder_input_ids)
|
| 876 |
+
decoder_mask_fingerprint: str | None = None
|
| 877 |
+
if decoder_attention_mask is not None:
|
| 878 |
+
if not isinstance(decoder_attention_mask, Tensor):
|
| 879 |
+
raise TypeError("decoder_attention_mask must be a tensor.")
|
| 880 |
+
if decoder_input_ids is None or decoder_attention_mask.shape != decoder_input_ids.shape:
|
| 881 |
+
raise ValueError("decoder_attention_mask must match decoder_input_ids shape.")
|
| 882 |
+
decoder_mask_fingerprint = tensor_sha256(decoder_attention_mask)
|
| 883 |
+
|
| 884 |
+
context: dict[str, Any] = {
|
| 885 |
+
"hidden_state_source": hidden_state_source,
|
| 886 |
+
"hidden_state_index": hidden_state_index,
|
| 887 |
+
"store_all_hidden_states": store_all_hidden_states,
|
| 888 |
+
"decoder_input_fingerprint": decoder_input_fingerprint,
|
| 889 |
+
"decoder_attention_mask_fingerprint": decoder_mask_fingerprint,
|
| 890 |
+
"decoder_alignment": "input-position" if hidden_state_source == "decoder" else None,
|
| 891 |
+
}
|
| 892 |
+
metadata_hook = getattr(model, "_embedding_metadata", None)
|
| 893 |
+
model_metadata: Mapping[str, Any] | None = None
|
| 894 |
+
if callable(metadata_hook):
|
| 895 |
+
model_metadata = metadata_hook(**context)
|
| 896 |
+
if not isinstance(model_metadata, Mapping):
|
| 897 |
+
raise TypeError("_embedding_metadata must return a mapping.")
|
| 898 |
+
context["model_embedding"] = _fingerprint_jsonable(model_metadata)
|
| 899 |
+
if hidden_state_source == "decoder":
|
| 900 |
+
has_decoder_batch = callable(getattr(model, "_embedding_batch", None))
|
| 901 |
+
declares_decoder_stack = (
|
| 902 |
+
model_metadata is not None and model_metadata.get("hidden_state_stack") == "decoder"
|
| 903 |
+
)
|
| 904 |
+
if not has_decoder_batch or not declares_decoder_stack:
|
| 905 |
+
raise ValueError(
|
| 906 |
+
f"{model.__class__.__name__} does not declare decoder embedding support."
|
| 907 |
+
)
|
| 908 |
+
return context, normalized_decoder_inputs
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def _planned_batches(
|
| 912 |
+
records: Sequence[EmbeddingInput],
|
| 913 |
+
positions: range,
|
| 914 |
+
*,
|
| 915 |
+
batch_size: int,
|
| 916 |
+
max_tokens_per_batch: int | None,
|
| 917 |
+
max_length: int | None,
|
| 918 |
+
truncate: bool,
|
| 919 |
+
) -> Iterator[list[int]]:
|
| 920 |
+
"""Length-bucket one bounded window while retaining stable output positions."""
|
| 921 |
+
|
| 922 |
+
def effective_length(position: int) -> int:
|
| 923 |
+
length = len(records[position].sequence)
|
| 924 |
+
return min(length, max_length) if truncate and max_length is not None else length
|
| 925 |
+
|
| 926 |
+
ordered = sorted(positions, key=lambda position: (-effective_length(position), position))
|
| 927 |
+
batch: list[int] = []
|
| 928 |
+
longest = 0
|
| 929 |
+
for position in ordered:
|
| 930 |
+
length = effective_length(position)
|
| 931 |
+
if max_tokens_per_batch is not None and length > max_tokens_per_batch:
|
| 932 |
+
raise ValueError(
|
| 933 |
+
f"Input at position {position} has {length} residues, exceeding "
|
| 934 |
+
f"max_tokens_per_batch={max_tokens_per_batch}."
|
| 935 |
+
)
|
| 936 |
+
candidate_longest = max(longest, length)
|
| 937 |
+
exceeds_tokens = (
|
| 938 |
+
max_tokens_per_batch is not None
|
| 939 |
+
and candidate_longest * (len(batch) + 1) > max_tokens_per_batch
|
| 940 |
+
)
|
| 941 |
+
if batch and (len(batch) >= batch_size or exceeds_tokens):
|
| 942 |
+
yield batch
|
| 943 |
+
batch = []
|
| 944 |
+
longest = 0
|
| 945 |
+
batch.append(position)
|
| 946 |
+
longest = max(longest, length)
|
| 947 |
+
if batch:
|
| 948 |
+
yield batch
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def embed_dataset(
|
| 952 |
+
model: Any,
|
| 953 |
+
inputs: (Iterable[str | EmbeddingInput | tuple[str, str]] | Mapping[str, str] | str | Path),
|
| 954 |
+
*,
|
| 955 |
+
batch_size: int = 2,
|
| 956 |
+
pooling: str | Sequence[str] | None = None,
|
| 957 |
+
full_embeddings: bool = False,
|
| 958 |
+
output: str | Path | None = None,
|
| 959 |
+
format: str = "safetensors",
|
| 960 |
+
resume: bool = True,
|
| 961 |
+
tokenizer: Any | None = None,
|
| 962 |
+
max_length: int | None = None,
|
| 963 |
+
truncate: bool = True,
|
| 964 |
+
dtype: torch.dtype | None = torch.float32,
|
| 965 |
+
shard_size: int = 2 * 1024**3,
|
| 966 |
+
model_state_fingerprint: str | None = None,
|
| 967 |
+
batch_window_size: int | None = None,
|
| 968 |
+
max_tokens_per_batch: int | None = None,
|
| 969 |
+
hidden_state_source: str = "encoder",
|
| 970 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 971 |
+
decoder_input_ids: Tensor | None = None,
|
| 972 |
+
decoder_attention_mask: Tensor | None = None,
|
| 973 |
+
_embedding_batch_fn: Callable[..., EmbeddingBatch] | None = None,
|
| 974 |
+
_embedding_batch_identity: Mapping[str, Any] | None = None,
|
| 975 |
+
_allowed_unsupported_pooling: Sequence[str] = (),
|
| 976 |
+
**model_kwargs: Any,
|
| 977 |
+
) -> EmbeddingResult:
|
| 978 |
+
"""Embed protein sequences with stable ordering and residue-only pooling."""
|
| 979 |
+
|
| 980 |
+
for name, value in (
|
| 981 |
+
("batch_size", batch_size),
|
| 982 |
+
("shard_size", shard_size),
|
| 983 |
+
):
|
| 984 |
+
if not isinstance(value, int) or isinstance(value, bool):
|
| 985 |
+
raise TypeError(f"{name} must be a positive integer.")
|
| 986 |
+
if value <= 0:
|
| 987 |
+
raise ValueError(f"{name} must be a positive integer.")
|
| 988 |
+
for optional_name, optional_value in (
|
| 989 |
+
("max_length", max_length),
|
| 990 |
+
("max_tokens_per_batch", max_tokens_per_batch),
|
| 991 |
+
("batch_window_size", batch_window_size),
|
| 992 |
+
):
|
| 993 |
+
if optional_value is not None and (
|
| 994 |
+
not isinstance(optional_value, int) or isinstance(optional_value, bool)
|
| 995 |
+
):
|
| 996 |
+
raise TypeError(f"{optional_name} must be a positive integer when provided.")
|
| 997 |
+
if optional_value is not None and optional_value <= 0:
|
| 998 |
+
raise ValueError(f"{optional_name} must be a positive integer when provided.")
|
| 999 |
+
for name, value in (
|
| 1000 |
+
("full_embeddings", full_embeddings),
|
| 1001 |
+
("resume", resume),
|
| 1002 |
+
("truncate", truncate),
|
| 1003 |
+
):
|
| 1004 |
+
if not isinstance(value, bool):
|
| 1005 |
+
raise TypeError(f"{name} must be a boolean.")
|
| 1006 |
+
if not isinstance(format, str):
|
| 1007 |
+
raise TypeError("format must be a string.")
|
| 1008 |
+
if output is not None and not isinstance(output, (str, Path)):
|
| 1009 |
+
raise TypeError("output must be a path or None.")
|
| 1010 |
+
if model_state_fingerprint is not None and (
|
| 1011 |
+
not isinstance(model_state_fingerprint, str) or not model_state_fingerprint
|
| 1012 |
+
):
|
| 1013 |
+
raise ValueError("model_state_fingerprint must be a non-empty string when provided.")
|
| 1014 |
+
if hidden_state_source not in {"encoder", "decoder"}:
|
| 1015 |
+
raise ValueError("hidden_state_source must be 'encoder' or 'decoder'.")
|
| 1016 |
+
hidden_state_index = model_kwargs.get("hidden_state_index", -1)
|
| 1017 |
+
if not isinstance(hidden_state_index, int) or isinstance(hidden_state_index, bool):
|
| 1018 |
+
raise TypeError("hidden_state_index must be an integer.")
|
| 1019 |
+
store_all_hidden_states = model_kwargs.get("store_all_hidden_states", False)
|
| 1020 |
+
if not isinstance(store_all_hidden_states, bool):
|
| 1021 |
+
raise TypeError("store_all_hidden_states must be a boolean.")
|
| 1022 |
+
if decoder_input_ids is not None:
|
| 1023 |
+
if not isinstance(decoder_input_ids, Tensor):
|
| 1024 |
+
raise TypeError("decoder_input_ids must be a tensor.")
|
| 1025 |
+
if decoder_input_ids.is_meta:
|
| 1026 |
+
raise ValueError("decoder_input_ids cannot be a meta tensor.")
|
| 1027 |
+
if decoder_input_ids.ndim != 2 or decoder_input_ids.shape[1] == 0:
|
| 1028 |
+
raise ValueError("decoder_input_ids must have non-empty shape (batch, sequence).")
|
| 1029 |
+
if decoder_input_ids.dtype not in {torch.int32, torch.int64}:
|
| 1030 |
+
raise TypeError("decoder_input_ids must use torch.int32 or torch.int64.")
|
| 1031 |
+
if decoder_attention_mask is not None:
|
| 1032 |
+
if not isinstance(decoder_attention_mask, Tensor):
|
| 1033 |
+
raise TypeError("decoder_attention_mask must be a tensor.")
|
| 1034 |
+
if decoder_attention_mask.is_meta:
|
| 1035 |
+
raise ValueError("decoder_attention_mask cannot be a meta tensor.")
|
| 1036 |
+
if decoder_attention_mask.is_complex() or not bool(
|
| 1037 |
+
torch.isfinite(decoder_attention_mask).all()
|
| 1038 |
+
):
|
| 1039 |
+
raise ValueError("decoder_attention_mask must contain finite binary values.")
|
| 1040 |
+
if not bool(((decoder_attention_mask == 0) | (decoder_attention_mask == 1)).all()):
|
| 1041 |
+
raise ValueError("decoder_attention_mask must contain finite binary values.")
|
| 1042 |
+
pooling_names = (
|
| 1043 |
+
(("mean",) if not full_embeddings else ())
|
| 1044 |
+
if pooling is None
|
| 1045 |
+
else ((pooling,) if isinstance(pooling, str) else tuple(pooling))
|
| 1046 |
+
)
|
| 1047 |
+
if full_embeddings and pooling is not None:
|
| 1048 |
+
raise ValueError("full_embeddings=True cannot be combined with pooling.")
|
| 1049 |
+
if not full_embeddings and not pooling_names:
|
| 1050 |
+
raise ValueError("pooling is required unless full_embeddings=True.")
|
| 1051 |
+
pooler = Pooler(pooling_names) if pooling_names else None
|
| 1052 |
+
|
| 1053 |
+
if batch_size <= 0:
|
| 1054 |
+
raise ValueError("batch_size must be positive.")
|
| 1055 |
+
if format == "pth" or (output is not None and Path(output).suffix.lower() == ".pth"):
|
| 1056 |
+
raise ValueError("Writing pickle-based .pth embeddings is not supported.")
|
| 1057 |
+
if format not in _SUPPORTED_STORAGE_FORMATS:
|
| 1058 |
+
raise ValueError("format must be 'safetensors' or 'sqlite'.")
|
| 1059 |
+
if max_length is not None and max_length <= 0:
|
| 1060 |
+
raise ValueError("max_length must be positive when provided.")
|
| 1061 |
+
if max_tokens_per_batch is not None and max_tokens_per_batch <= 0:
|
| 1062 |
+
raise ValueError("max_tokens_per_batch must be positive when provided.")
|
| 1063 |
+
if not isinstance(dtype, (torch.dtype, type(None))):
|
| 1064 |
+
raise TypeError("dtype must be a torch.dtype or None.")
|
| 1065 |
+
if batch_window_size is not None and batch_window_size <= 0:
|
| 1066 |
+
raise ValueError("batch_window_size must be positive when provided.")
|
| 1067 |
+
if _embedding_batch_fn is not None and not callable(_embedding_batch_fn):
|
| 1068 |
+
raise TypeError("_embedding_batch_fn must be callable when provided.")
|
| 1069 |
+
if _embedding_batch_fn is not None and _embedding_batch_identity is None:
|
| 1070 |
+
raise ValueError(
|
| 1071 |
+
"_embedding_batch_identity is required with _embedding_batch_fn so persisted "
|
| 1072 |
+
"runs bind the family-specific embedding behavior."
|
| 1073 |
+
)
|
| 1074 |
+
if _embedding_batch_identity is not None and not isinstance(_embedding_batch_identity, Mapping):
|
| 1075 |
+
raise TypeError("_embedding_batch_identity must be a mapping when provided.")
|
| 1076 |
+
if isinstance(_allowed_unsupported_pooling, (str, bytes)) or not isinstance(
|
| 1077 |
+
_allowed_unsupported_pooling, Sequence
|
| 1078 |
+
):
|
| 1079 |
+
raise TypeError("_allowed_unsupported_pooling must be a sequence of pooler names.")
|
| 1080 |
+
if not all(isinstance(name, str) for name in _allowed_unsupported_pooling):
|
| 1081 |
+
raise TypeError("_allowed_unsupported_pooling must contain only strings.")
|
| 1082 |
+
allowed_unsupported_pooling = frozenset(_allowed_unsupported_pooling)
|
| 1083 |
+
if allowed_unsupported_pooling and _embedding_batch_fn is None:
|
| 1084 |
+
raise ValueError(
|
| 1085 |
+
"_allowed_unsupported_pooling is only valid with a family-specific _embedding_batch_fn."
|
| 1086 |
+
)
|
| 1087 |
+
resolved_batch_window_size = (
|
| 1088 |
+
batch_size * _DEFAULT_BATCH_WINDOW_MULTIPLIER
|
| 1089 |
+
if batch_window_size is None
|
| 1090 |
+
else batch_window_size
|
| 1091 |
+
)
|
| 1092 |
+
if resolved_batch_window_size < batch_size:
|
| 1093 |
+
raise ValueError("batch_window_size must be at least batch_size.")
|
| 1094 |
+
records = _normalize_inputs(inputs, disk_backed=output is not None)
|
| 1095 |
+
_validate_untruncated_lengths(
|
| 1096 |
+
records,
|
| 1097 |
+
max_length=max_length,
|
| 1098 |
+
truncate=truncate,
|
| 1099 |
+
)
|
| 1100 |
+
pooling_names = (
|
| 1101 |
+
(("mean",) if not full_embeddings else ())
|
| 1102 |
+
if pooling is None
|
| 1103 |
+
else ((pooling,) if isinstance(pooling, str) else tuple(pooling))
|
| 1104 |
+
)
|
| 1105 |
+
if full_embeddings:
|
| 1106 |
+
if pooling is not None:
|
| 1107 |
+
raise ValueError("full_embeddings=True cannot be combined with pooling.")
|
| 1108 |
+
elif not pooling_names:
|
| 1109 |
+
raise ValueError("pooling is required unless full_embeddings=True.")
|
| 1110 |
+
store_all_hidden_states = bool(model_kwargs.get("store_all_hidden_states", False))
|
| 1111 |
+
if store_all_hidden_states and not full_embeddings:
|
| 1112 |
+
raise ValueError("store_all_hidden_states=True requires full_embeddings=True.")
|
| 1113 |
+
|
| 1114 |
+
unsupported = set(getattr(model, "embedding_unsupported_pooling", ()))
|
| 1115 |
+
unknown_pooling_overrides = allowed_unsupported_pooling.difference(unsupported)
|
| 1116 |
+
if unknown_pooling_overrides:
|
| 1117 |
+
raise ValueError(
|
| 1118 |
+
"_allowed_unsupported_pooling may only override poolers declared unsupported "
|
| 1119 |
+
f"by the model; unknown overrides: {sorted(unknown_pooling_overrides)}."
|
| 1120 |
+
)
|
| 1121 |
+
unsupported.difference_update(allowed_unsupported_pooling)
|
| 1122 |
+
requested_unsupported = unsupported.intersection(pooling_names)
|
| 1123 |
+
if requested_unsupported:
|
| 1124 |
+
raise ValueError(
|
| 1125 |
+
f"{model.__class__.__name__} does not support pooling operations "
|
| 1126 |
+
f"{sorted(requested_unsupported)}."
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
# Constructing the pooler validates names and duplicate operations before
|
| 1130 |
+
# any checkpoint hashing, tokenization, or inference occurs.
|
| 1131 |
+
pooler = Pooler(pooling_names) if pooling_names else None
|
| 1132 |
+
embedding_context, normalized_decoder_inputs = _embedding_context(
|
| 1133 |
+
model,
|
| 1134 |
+
records,
|
| 1135 |
+
hidden_state_source=hidden_state_source,
|
| 1136 |
+
decoder_inputs=decoder_inputs,
|
| 1137 |
+
decoder_input_ids=decoder_input_ids,
|
| 1138 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1139 |
+
model_kwargs=model_kwargs,
|
| 1140 |
+
)
|
| 1141 |
+
if _embedding_batch_identity is not None:
|
| 1142 |
+
embedding_context["family_adapter"] = _fingerprint_jsonable(_embedding_batch_identity)
|
| 1143 |
+
if allowed_unsupported_pooling:
|
| 1144 |
+
embedding_context["family_adapter_pooling_override"] = sorted(
|
| 1145 |
+
allowed_unsupported_pooling
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
tokenizer_metadata = _tokenizer_metadata(model, tokenizer)
|
| 1149 |
+
(
|
| 1150 |
+
input_fingerprint,
|
| 1151 |
+
run_fingerprint,
|
| 1152 |
+
resolved_model_state_fingerprint,
|
| 1153 |
+
model_state_fingerprint_source,
|
| 1154 |
+
) = _run_fingerprint(
|
| 1155 |
+
model,
|
| 1156 |
+
records,
|
| 1157 |
+
pooling=pooling_names,
|
| 1158 |
+
full_embeddings=full_embeddings,
|
| 1159 |
+
max_length=max_length,
|
| 1160 |
+
truncate=truncate,
|
| 1161 |
+
dtype=dtype,
|
| 1162 |
+
model_kwargs=model_kwargs,
|
| 1163 |
+
tokenizer_metadata=tokenizer_metadata,
|
| 1164 |
+
model_state_fingerprint=model_state_fingerprint,
|
| 1165 |
+
persist_output=output is not None,
|
| 1166 |
+
embedding_context=embedding_context,
|
| 1167 |
+
batch_size=batch_size,
|
| 1168 |
+
batch_window_size=resolved_batch_window_size,
|
| 1169 |
+
max_tokens_per_batch=max_tokens_per_batch,
|
| 1170 |
+
)
|
| 1171 |
+
output_already_exists = output is not None and _output_exists(output, format)
|
| 1172 |
+
existing: EmbeddingResult | None = None
|
| 1173 |
+
start_position = 0
|
| 1174 |
+
if output is not None and resume and output_already_exists:
|
| 1175 |
+
if format == "sqlite":
|
| 1176 |
+
try:
|
| 1177 |
+
existing = load_sqlite_result(output, run_id=run_fingerprint)
|
| 1178 |
+
except KeyError:
|
| 1179 |
+
existing = load_result(output, format=format)
|
| 1180 |
+
else:
|
| 1181 |
+
existing = load_result(output, format=format)
|
| 1182 |
+
if existing.metadata.get("fingerprint_schema_version") != (_RUN_FINGERPRINT_SCHEMA_VERSION):
|
| 1183 |
+
raise ValueError(
|
| 1184 |
+
"Existing embeddings use an incompatible run fingerprint schema; "
|
| 1185 |
+
"choose another output or set resume=False."
|
| 1186 |
+
)
|
| 1187 |
+
if existing.metadata.get("run_fingerprint") != run_fingerprint:
|
| 1188 |
+
raise ValueError(
|
| 1189 |
+
"Existing embeddings were produced by a different run fingerprint; "
|
| 1190 |
+
"choose another output or set resume=False."
|
| 1191 |
+
)
|
| 1192 |
+
if len(existing) > len(records):
|
| 1193 |
+
raise ValueError(
|
| 1194 |
+
"Existing embeddings are not an ordered prefix of the requested inputs."
|
| 1195 |
+
)
|
| 1196 |
+
prefix_matches = all(
|
| 1197 |
+
(observed.id, observed.sequence) == (expected.id, expected.sequence)
|
| 1198 |
+
for expected, observed in zip(records, existing, strict=False)
|
| 1199 |
+
)
|
| 1200 |
+
if not prefix_matches:
|
| 1201 |
+
raise ValueError(
|
| 1202 |
+
"Existing embeddings are not an ordered prefix of the requested inputs."
|
| 1203 |
+
)
|
| 1204 |
+
if len(existing) == len(records) and existing.metadata.get("complete", True):
|
| 1205 |
+
return existing
|
| 1206 |
+
start_position = len(existing)
|
| 1207 |
+
|
| 1208 |
+
sqlite_run_id: str | None = None
|
| 1209 |
+
sqlite_replace_on_first_commit = False
|
| 1210 |
+
sqlite_initial_metadata: dict[str, Any] | None = None
|
| 1211 |
+
if output is not None and format == "sqlite":
|
| 1212 |
+
sqlite_initial_metadata = {
|
| 1213 |
+
"format_version": 1,
|
| 1214 |
+
"fingerprint_schema_version": _RUN_FINGERPRINT_SCHEMA_VERSION,
|
| 1215 |
+
"run_fingerprint": run_fingerprint,
|
| 1216 |
+
"input_fingerprint": input_fingerprint,
|
| 1217 |
+
"model_state_fingerprint": resolved_model_state_fingerprint,
|
| 1218 |
+
"model_state_fingerprint_source": model_state_fingerprint_source,
|
| 1219 |
+
"complete": False,
|
| 1220 |
+
}
|
| 1221 |
+
sqlite_run_id = run_fingerprint
|
| 1222 |
+
if not resume and output_already_exists:
|
| 1223 |
+
try:
|
| 1224 |
+
load_sqlite_result(output, run_id=run_fingerprint)
|
| 1225 |
+
except KeyError:
|
| 1226 |
+
pass
|
| 1227 |
+
else:
|
| 1228 |
+
# Keep an exact prior run readable until replacement inference
|
| 1229 |
+
# has produced the first complete commit window.
|
| 1230 |
+
sqlite_replace_on_first_commit = True
|
| 1231 |
+
if not sqlite_replace_on_first_commit:
|
| 1232 |
+
initialize_sqlite_run(
|
| 1233 |
+
output,
|
| 1234 |
+
sqlite_initial_metadata,
|
| 1235 |
+
resume=resume,
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
stream_safetensors = output is not None and format == "safetensors"
|
| 1239 |
+
attention_backend = _attention_backend(model)
|
| 1240 |
+
output_records: list[EmbeddingRecord] = (
|
| 1241 |
+
[] if sqlite_run_id is not None or stream_safetensors else list(existing or ())
|
| 1242 |
+
)
|
| 1243 |
+
output_descriptors: list[dict[str, Any]] | None = [] if output is None else None
|
| 1244 |
+
pool_slices: dict[str, tuple[int, int]] = {}
|
| 1245 |
+
if existing and pooler is not None:
|
| 1246 |
+
pooled_width = existing[0].load_tensor().shape[-1]
|
| 1247 |
+
if pooled_width % len(pooling_names) != 0:
|
| 1248 |
+
raise ValueError("Stored pooled width is inconsistent with pooling metadata.")
|
| 1249 |
+
pool_slices = pooler.output_slices(pooled_width // len(pooling_names))
|
| 1250 |
+
|
| 1251 |
+
safetensors_writer: SafetensorsStreamWriter | None = None
|
| 1252 |
+
if stream_safetensors:
|
| 1253 |
+
if output is None:
|
| 1254 |
+
raise RuntimeError("Safetensors streaming was enabled without an output destination.")
|
| 1255 |
+
transactional_overwrite = output_already_exists and not resume
|
| 1256 |
+
safetensors_writer = SafetensorsStreamWriter(
|
| 1257 |
+
output,
|
| 1258 |
+
{
|
| 1259 |
+
"format_version": 1,
|
| 1260 |
+
"fingerprint_schema_version": _RUN_FINGERPRINT_SCHEMA_VERSION,
|
| 1261 |
+
"run_fingerprint": run_fingerprint,
|
| 1262 |
+
"input_fingerprint": input_fingerprint,
|
| 1263 |
+
"model_state_fingerprint": resolved_model_state_fingerprint,
|
| 1264 |
+
"model_state_fingerprint_source": model_state_fingerprint_source,
|
| 1265 |
+
"complete": False,
|
| 1266 |
+
},
|
| 1267 |
+
shard_size=shard_size,
|
| 1268 |
+
existing=existing or (),
|
| 1269 |
+
reuse_existing=bool(resume and existing is not None),
|
| 1270 |
+
publish_initial=not transactional_overwrite,
|
| 1271 |
+
publish_incremental=not transactional_overwrite,
|
| 1272 |
+
)
|
| 1273 |
+
need_attentions = "parti" in pooling_names
|
| 1274 |
+
|
| 1275 |
+
config = getattr(model, "config", None)
|
| 1276 |
+
model_type = str(getattr(config, "model_type", "")).lower()
|
| 1277 |
+
resolved_tokenizer = tokenizer if tokenizer is not None else getattr(model, "tokenizer", None)
|
| 1278 |
+
with _temporary_eval(model), torch.inference_mode():
|
| 1279 |
+
for window_start in range(start_position, len(records), resolved_batch_window_size):
|
| 1280 |
+
window_stop = min(window_start + resolved_batch_window_size, len(records))
|
| 1281 |
+
window_records = records[window_start:window_stop]
|
| 1282 |
+
if not isinstance(window_records, Sequence):
|
| 1283 |
+
raise RuntimeError("The immutable embedding spool returned a non-sequence window.")
|
| 1284 |
+
window_results: dict[int, EmbeddingRecord] = {}
|
| 1285 |
+
for local_positions in _planned_batches(
|
| 1286 |
+
window_records,
|
| 1287 |
+
range(len(window_records)),
|
| 1288 |
+
batch_size=batch_size,
|
| 1289 |
+
max_tokens_per_batch=max_tokens_per_batch,
|
| 1290 |
+
max_length=max_length,
|
| 1291 |
+
truncate=truncate,
|
| 1292 |
+
):
|
| 1293 |
+
batch_positions = [window_start + position for position in local_positions]
|
| 1294 |
+
batch_records = [window_records[position] for position in local_positions]
|
| 1295 |
+
sequences = [
|
| 1296 |
+
record.sequence[:max_length]
|
| 1297 |
+
if truncate and max_length is not None
|
| 1298 |
+
else record.sequence
|
| 1299 |
+
for record in batch_records
|
| 1300 |
+
]
|
| 1301 |
+
batch_model_kwargs = dict(model_kwargs)
|
| 1302 |
+
if model_type == "fast_ankh" or hidden_state_source == "decoder":
|
| 1303 |
+
batch_model_kwargs["hidden_state_source"] = hidden_state_source
|
| 1304 |
+
if normalized_decoder_inputs is not None:
|
| 1305 |
+
batch_model_kwargs["decoder_inputs"] = [
|
| 1306 |
+
normalized_decoder_inputs[position] for position in batch_positions
|
| 1307 |
+
]
|
| 1308 |
+
if decoder_input_ids is not None:
|
| 1309 |
+
indices = torch.tensor(
|
| 1310 |
+
batch_positions,
|
| 1311 |
+
device=decoder_input_ids.device,
|
| 1312 |
+
dtype=torch.long,
|
| 1313 |
+
)
|
| 1314 |
+
batch_model_kwargs["decoder_input_ids"] = decoder_input_ids.index_select(
|
| 1315 |
+
0, indices
|
| 1316 |
+
)
|
| 1317 |
+
if decoder_attention_mask is not None:
|
| 1318 |
+
indices = torch.tensor(
|
| 1319 |
+
batch_positions,
|
| 1320 |
+
device=decoder_attention_mask.device,
|
| 1321 |
+
dtype=torch.long,
|
| 1322 |
+
)
|
| 1323 |
+
batch_model_kwargs["decoder_attention_mask"] = (
|
| 1324 |
+
decoder_attention_mask.index_select(0, indices)
|
| 1325 |
+
)
|
| 1326 |
+
custom_batch = _embedding_batch_fn or getattr(model, "_embedding_batch", None)
|
| 1327 |
+
if custom_batch is not None:
|
| 1328 |
+
if model_type == "fast_ankh":
|
| 1329 |
+
batch = custom_batch(
|
| 1330 |
+
sequences,
|
| 1331 |
+
tokenizer=resolved_tokenizer,
|
| 1332 |
+
max_length=max_length,
|
| 1333 |
+
truncate=truncate,
|
| 1334 |
+
need_attentions=need_attentions,
|
| 1335 |
+
**batch_model_kwargs,
|
| 1336 |
+
)
|
| 1337 |
+
else:
|
| 1338 |
+
batch = custom_batch(sequences, **batch_model_kwargs)
|
| 1339 |
+
if not isinstance(batch, EmbeddingBatch):
|
| 1340 |
+
raise TypeError("_embedding_batch must return EmbeddingBatch.")
|
| 1341 |
+
else:
|
| 1342 |
+
batch = _generic_embedding_batch(
|
| 1343 |
+
model,
|
| 1344 |
+
sequences,
|
| 1345 |
+
tokenizer=tokenizer,
|
| 1346 |
+
max_length=max_length,
|
| 1347 |
+
truncate=truncate,
|
| 1348 |
+
need_attentions=need_attentions,
|
| 1349 |
+
model_kwargs=batch_model_kwargs,
|
| 1350 |
+
)
|
| 1351 |
+
X = batch.X
|
| 1352 |
+
raw_mask = batch.residue_mask
|
| 1353 |
+
if not isinstance(X, Tensor) or not isinstance(raw_mask, Tensor):
|
| 1354 |
+
raise TypeError("Embedding batches must provide Tensor X and residue_mask.")
|
| 1355 |
+
if X.is_meta or raw_mask.is_meta:
|
| 1356 |
+
raise ValueError("Embedding batches cannot contain meta tensors.")
|
| 1357 |
+
if not X.is_floating_point():
|
| 1358 |
+
raise TypeError("Embedding batches must use a floating-point X dtype.")
|
| 1359 |
+
if raw_mask.is_complex() or not bool(torch.isfinite(raw_mask).all()):
|
| 1360 |
+
raise ValueError("Embedding residue_mask must contain finite binary values.")
|
| 1361 |
+
if not bool(((raw_mask == 0) | (raw_mask == 1)).all()):
|
| 1362 |
+
raise ValueError("Embedding residue_mask must contain finite binary values.")
|
| 1363 |
+
M = raw_mask.to(device=X.device, dtype=torch.bool)
|
| 1364 |
+
valid_X_shape = (
|
| 1365 |
+
X.ndim == 3
|
| 1366 |
+
and X.shape[0] == len(batch_records)
|
| 1367 |
+
and X.shape[-1] > 0
|
| 1368 |
+
and M.shape == X.shape[:2]
|
| 1369 |
+
)
|
| 1370 |
+
valid_all_states_shape = (
|
| 1371 |
+
X.ndim == 4
|
| 1372 |
+
and store_all_hidden_states
|
| 1373 |
+
and full_embeddings
|
| 1374 |
+
and X.shape[0] == len(batch_records)
|
| 1375 |
+
and X.shape[1] > 0
|
| 1376 |
+
and X.shape[-1] > 0
|
| 1377 |
+
and M.shape == (X.shape[0], X.shape[2])
|
| 1378 |
+
)
|
| 1379 |
+
if not (valid_X_shape or valid_all_states_shape):
|
| 1380 |
+
raise ValueError(
|
| 1381 |
+
"Embedding batches must provide X with shape (b, l, d), or "
|
| 1382 |
+
"(b, states, l, d) when storing all hidden states, and "
|
| 1383 |
+
"residue_mask with shape (b, l)."
|
| 1384 |
+
)
|
| 1385 |
+
if not bool(M.any(dim=1).all()):
|
| 1386 |
+
raise ValueError("Every embedding sample must contain a biological residue.")
|
| 1387 |
+
finite_selected = (
|
| 1388 |
+
torch.isfinite(X) | ~M.unsqueeze(-1)
|
| 1389 |
+
if X.ndim == 3
|
| 1390 |
+
else torch.isfinite(X) | ~M[:, None, :, None]
|
| 1391 |
+
)
|
| 1392 |
+
if not bool(finite_selected.all()):
|
| 1393 |
+
raise ValueError("Biological residue embeddings produced non-finite output.")
|
| 1394 |
+
if need_attentions:
|
| 1395 |
+
# Validate the biological graph only after mask integrity is established.
|
| 1396 |
+
_validate_parti_length(M)
|
| 1397 |
+
if dtype is not None:
|
| 1398 |
+
X = X.to(dtype=dtype)
|
| 1399 |
+
|
| 1400 |
+
if full_embeddings:
|
| 1401 |
+
if X.ndim == 4:
|
| 1402 |
+
values = [
|
| 1403 |
+
X_i[:, M_i, :].detach().cpu() for X_i, M_i in zip(X, M, strict=True)
|
| 1404 |
+
]
|
| 1405 |
+
else:
|
| 1406 |
+
values = [X_i[M_i].detach().cpu() for X_i, M_i in zip(X, M, strict=True)]
|
| 1407 |
+
else:
|
| 1408 |
+
if pooler is None:
|
| 1409 |
+
raise RuntimeError(
|
| 1410 |
+
"Pooled embedding output was requested without an initialized pooler."
|
| 1411 |
+
)
|
| 1412 |
+
Y = pooler(
|
| 1413 |
+
X,
|
| 1414 |
+
M,
|
| 1415 |
+
attentions=batch.attentions,
|
| 1416 |
+
attention_backend=attention_backend,
|
| 1417 |
+
)
|
| 1418 |
+
pool_slices = pooler.output_slices(X.shape[-1])
|
| 1419 |
+
values = list(Y.detach().cpu().unbind(0))
|
| 1420 |
+
for position, record, value in zip(
|
| 1421 |
+
batch_positions, batch_records, values, strict=True
|
| 1422 |
+
):
|
| 1423 |
+
window_results[position] = EmbeddingRecord(record.id, record.sequence, value)
|
| 1424 |
+
|
| 1425 |
+
new_records = [
|
| 1426 |
+
window_results[position] for position in range(window_start, window_stop)
|
| 1427 |
+
]
|
| 1428 |
+
if output_descriptors is not None:
|
| 1429 |
+
output_descriptors.extend(
|
| 1430 |
+
_output_descriptor(window_start + offset, record)
|
| 1431 |
+
for offset, record in enumerate(new_records)
|
| 1432 |
+
)
|
| 1433 |
+
if output is not None and sqlite_run_id is not None:
|
| 1434 |
+
append_sqlite_records(
|
| 1435 |
+
output,
|
| 1436 |
+
sqlite_run_id,
|
| 1437 |
+
window_start,
|
| 1438 |
+
new_records,
|
| 1439 |
+
replace_metadata=(
|
| 1440 |
+
sqlite_initial_metadata if sqlite_replace_on_first_commit else None
|
| 1441 |
+
),
|
| 1442 |
+
)
|
| 1443 |
+
sqlite_replace_on_first_commit = False
|
| 1444 |
+
elif safetensors_writer is not None:
|
| 1445 |
+
safetensors_writer.append(new_records)
|
| 1446 |
+
else:
|
| 1447 |
+
output_records.extend(new_records)
|
| 1448 |
+
|
| 1449 |
+
software_versions = _software_versions()
|
| 1450 |
+
projection = getattr(model, "embedding_projection", None)
|
| 1451 |
+
resolved_layer = getattr(
|
| 1452 |
+
model,
|
| 1453 |
+
"embedding_layer",
|
| 1454 |
+
model_kwargs.get("hidden_state_index", -1),
|
| 1455 |
+
)
|
| 1456 |
+
token_policy = getattr(
|
| 1457 |
+
model,
|
| 1458 |
+
"embedding_token_policy",
|
| 1459 |
+
{
|
| 1460 |
+
"unit": "residue",
|
| 1461 |
+
"include": ["biological residues"],
|
| 1462 |
+
"exclude": [
|
| 1463 |
+
"BOS",
|
| 1464 |
+
"EOS",
|
| 1465 |
+
"padding",
|
| 1466 |
+
"chain delimiters",
|
| 1467 |
+
"non-protein tokens",
|
| 1468 |
+
],
|
| 1469 |
+
},
|
| 1470 |
+
)
|
| 1471 |
+
model_identity = _model_identity_metadata(model)
|
| 1472 |
+
metadata: dict[str, Any] = {
|
| 1473 |
+
"format_version": 1,
|
| 1474 |
+
"fingerprint_schema_version": _RUN_FINGERPRINT_SCHEMA_VERSION,
|
| 1475 |
+
"run_fingerprint": run_fingerprint,
|
| 1476 |
+
"input_fingerprint": input_fingerprint,
|
| 1477 |
+
"model_state_fingerprint": resolved_model_state_fingerprint,
|
| 1478 |
+
"model_state_fingerprint_source": model_state_fingerprint_source,
|
| 1479 |
+
"model_class": f"{model.__class__.__module__}.{model.__class__.__qualname__}",
|
| 1480 |
+
**model_identity,
|
| 1481 |
+
"dtype": str(dtype).removeprefix("torch.") if dtype is not None else "model",
|
| 1482 |
+
"attention_backend": attention_backend,
|
| 1483 |
+
"attention_kernel": _attention_kernel_metadata(attention_backend),
|
| 1484 |
+
"layer": resolved_layer,
|
| 1485 |
+
"projection": projection,
|
| 1486 |
+
"esmc_source": getattr(model, "_esmc_source", None),
|
| 1487 |
+
"esmc_revision": getattr(model, "_esmc_source_revision", None),
|
| 1488 |
+
"esmc_files": getattr(model, "_esmc_source_files", None),
|
| 1489 |
+
"token_policy": token_policy,
|
| 1490 |
+
"tokenizer": tokenizer_metadata,
|
| 1491 |
+
**embedding_context,
|
| 1492 |
+
"pooling": list(pooling_names),
|
| 1493 |
+
"pool_slices": pool_slices,
|
| 1494 |
+
"full_embeddings": full_embeddings,
|
| 1495 |
+
"max_length": max_length,
|
| 1496 |
+
"truncate": truncate,
|
| 1497 |
+
"truncation": {"enabled": truncate, "max_length": max_length},
|
| 1498 |
+
"batching": {
|
| 1499 |
+
"batch_size": batch_size,
|
| 1500 |
+
"batch_window_size": resolved_batch_window_size,
|
| 1501 |
+
"max_tokens_per_batch": max_tokens_per_batch,
|
| 1502 |
+
"input_storage": ("disk-spool" if isinstance(records, _InputSpool) else "memory"),
|
| 1503 |
+
"ordering": "bounded-length-bucketed-stable-output",
|
| 1504 |
+
"resume_commit_granularity": (
|
| 1505 |
+
"not-applicable"
|
| 1506 |
+
if output is None
|
| 1507 |
+
else "batch-window"
|
| 1508 |
+
if format == "sqlite"
|
| 1509 |
+
else "shard-flush"
|
| 1510 |
+
),
|
| 1511 |
+
},
|
| 1512 |
+
"residue_mask_policy": "biological-residues-only",
|
| 1513 |
+
"record_count": len(records),
|
| 1514 |
+
"descriptor_index": (
|
| 1515 |
+
"memory-metadata"
|
| 1516 |
+
if output is None
|
| 1517 |
+
else "sqlite-records"
|
| 1518 |
+
if format == "sqlite"
|
| 1519 |
+
else "safetensors-generation-index"
|
| 1520 |
+
),
|
| 1521 |
+
"storage_format": format if output is not None else "memory",
|
| 1522 |
+
"software": software_versions,
|
| 1523 |
+
"execution": _execution_identity_metadata(model),
|
| 1524 |
+
"adapter": _adapter_identity_metadata(model),
|
| 1525 |
+
"torch_version": software_versions["torch"],
|
| 1526 |
+
"transformers_version": software_versions["transformers"],
|
| 1527 |
+
"complete": True,
|
| 1528 |
+
}
|
| 1529 |
+
if output_descriptors is not None:
|
| 1530 |
+
metadata["outputs"] = output_descriptors
|
| 1531 |
+
metadata["tensor_hashes"] = [item["sha256"] for item in output_descriptors]
|
| 1532 |
+
status = getattr(model, "esmc_precision_status", None)
|
| 1533 |
+
if status is not None:
|
| 1534 |
+
metadata["esmc_precision"] = status.as_dict() if hasattr(status, "as_dict") else status
|
| 1535 |
+
if output is not None and sqlite_run_id is not None:
|
| 1536 |
+
update_sqlite_run_metadata(output, sqlite_run_id, metadata)
|
| 1537 |
+
return load_sqlite_result(output, run_id=sqlite_run_id)
|
| 1538 |
+
if safetensors_writer is not None:
|
| 1539 |
+
return safetensors_writer.publish(complete=True, metadata=metadata)
|
| 1540 |
+
result = EmbeddingResult(output_records, metadata)
|
| 1541 |
+
if output is not None:
|
| 1542 |
+
return save_result(result, output, format=format, shard_size=shard_size)
|
| 1543 |
+
return result
|
| 1544 |
+
|
| 1545 |
+
|
| 1546 |
+
class EmbeddingMixin:
|
| 1547 |
+
"""Small delegation mixin shared by FastPLMs model classes."""
|
| 1548 |
+
|
| 1549 |
+
def embed_dataset(self, inputs: Any, **kwargs: Any) -> EmbeddingResult:
|
| 1550 |
+
return embed_dataset(self, inputs, **kwargs)
|
| 1551 |
+
|
| 1552 |
+
|
| 1553 |
+
__all__ = [
|
| 1554 |
+
"EmbeddingMixin",
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lossless, reproducible storage for :mod:`fastplms.embeddings`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import sqlite3
|
| 9 |
+
import struct
|
| 10 |
+
from bisect import bisect_right
|
| 11 |
+
from collections.abc import Iterable, Iterator, Sequence
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, cast, overload
|
| 14 |
+
from uuid import uuid4
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
|
| 20 |
+
from .types import (
|
| 21 |
+
EmbeddingRecord,
|
| 22 |
+
EmbeddingResult,
|
| 23 |
+
LazyTensorReference,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
_DTYPE_NAMES: dict[torch.dtype, str] = {
|
| 27 |
+
torch.float16: "float16",
|
| 28 |
+
torch.bfloat16: "bfloat16",
|
| 29 |
+
torch.float32: "float32",
|
| 30 |
+
torch.float64: "float64",
|
| 31 |
+
torch.int64: "int64",
|
| 32 |
+
torch.int32: "int32",
|
| 33 |
+
torch.int16: "int16",
|
| 34 |
+
torch.int8: "int8",
|
| 35 |
+
torch.uint8: "uint8",
|
| 36 |
+
torch.bool: "bool",
|
| 37 |
+
}
|
| 38 |
+
_NAME_DTYPES = {name: dtype for dtype, name in _DTYPE_NAMES.items()}
|
| 39 |
+
DEFAULT_SHARD_SIZE = 2 * 1024**3
|
| 40 |
+
_MAX_RECORDS_PER_DESCRIPTOR_SHARD = 1_024
|
| 41 |
+
_TENSOR_HASH_CHUNK_BYTES = 16 * 1024**2
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _jsonable(value: Any) -> Any:
|
| 45 |
+
if isinstance(value, dict):
|
| 46 |
+
return {str(key): _jsonable(item) for key, item in value.items()}
|
| 47 |
+
if isinstance(value, (list, tuple)):
|
| 48 |
+
return [_jsonable(item) for item in value]
|
| 49 |
+
if isinstance(value, Path):
|
| 50 |
+
return str(value)
|
| 51 |
+
if isinstance(value, torch.dtype):
|
| 52 |
+
return str(value).removeprefix("torch.")
|
| 53 |
+
if isinstance(value, torch.device):
|
| 54 |
+
return str(value)
|
| 55 |
+
if value is None or isinstance(value, (str, int, float, bool)):
|
| 56 |
+
return value
|
| 57 |
+
return repr(value)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _persistent_metadata(
|
| 61 |
+
metadata: dict[str, Any],
|
| 62 |
+
*,
|
| 63 |
+
descriptor_index: str,
|
| 64 |
+
record_count: int | None = None,
|
| 65 |
+
) -> dict[str, Any]:
|
| 66 |
+
"""Remove per-record copies from metadata and identify the authoritative index."""
|
| 67 |
+
|
| 68 |
+
cleaned_value = _jsonable(metadata)
|
| 69 |
+
if not isinstance(cleaned_value, dict):
|
| 70 |
+
raise TypeError("Embedding metadata must serialize to a JSON object.")
|
| 71 |
+
cleaned: dict[str, Any] = cleaned_value
|
| 72 |
+
cleaned.pop("outputs", None)
|
| 73 |
+
cleaned.pop("tensor_hashes", None)
|
| 74 |
+
cleaned["descriptor_index"] = descriptor_index
|
| 75 |
+
if record_count is not None:
|
| 76 |
+
cleaned["record_count"] = record_count
|
| 77 |
+
return cleaned
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _tensor_bytes(X: Tensor) -> bytes:
|
| 81 |
+
"""Return the exact contiguous byte representation of X."""
|
| 82 |
+
|
| 83 |
+
X = X.detach().cpu().contiguous()
|
| 84 |
+
return X.view(torch.uint8).numpy().tobytes()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _bounded_tensor_chunks(X: Tensor, max_bytes: int) -> Iterator[Tensor]:
|
| 88 |
+
"""Yield row-major CPU chunks without materializing one full byte string."""
|
| 89 |
+
|
| 90 |
+
flattened = X.detach().to(device="cpu").reshape(-1)
|
| 91 |
+
if flattened.numel() == 0:
|
| 92 |
+
return
|
| 93 |
+
chunk_elements = max(1, max_bytes // flattened.element_size())
|
| 94 |
+
for start in range(0, flattened.numel(), chunk_elements):
|
| 95 |
+
chunk = flattened[start : start + chunk_elements]
|
| 96 |
+
if chunk.stride(0) != 1:
|
| 97 |
+
chunk = chunk.clone(memory_format=torch.contiguous_format)
|
| 98 |
+
yield chunk
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _tensor_hash_chunks(X: Tensor) -> Iterator[bytes]:
|
| 102 |
+
for chunk in _bounded_tensor_chunks(X, _TENSOR_HASH_CHUNK_BYTES):
|
| 103 |
+
yield chunk.view(torch.uint8).numpy().tobytes()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def tensor_sha256(X: Tensor) -> str:
|
| 107 |
+
"""Hash dtype, shape, and exact tensor bytes."""
|
| 108 |
+
|
| 109 |
+
if not isinstance(X, Tensor):
|
| 110 |
+
raise TypeError("X must be a tensor.")
|
| 111 |
+
if X.dtype not in _DTYPE_NAMES:
|
| 112 |
+
raise TypeError(f"Unsupported tensor dtype {X.dtype}.")
|
| 113 |
+
if X.is_meta:
|
| 114 |
+
raise ValueError("Cannot hash a meta tensor without storage.")
|
| 115 |
+
if X.layout != torch.strided:
|
| 116 |
+
raise TypeError("Only strided tensors can be hashed.")
|
| 117 |
+
digest = hashlib.sha256()
|
| 118 |
+
digest.update(_DTYPE_NAMES[X.dtype].encode())
|
| 119 |
+
digest.update(json.dumps(tuple(X.shape)).encode())
|
| 120 |
+
for chunk in _tensor_hash_chunks(X):
|
| 121 |
+
digest.update(chunk)
|
| 122 |
+
return digest.hexdigest()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _encode_tensor(X: Tensor) -> tuple[str, str, bytes]:
|
| 126 |
+
if X.dtype not in _DTYPE_NAMES:
|
| 127 |
+
raise TypeError(f"Unsupported tensor dtype {X.dtype}.")
|
| 128 |
+
shape = json.dumps(tuple(X.shape), separators=(",", ":"))
|
| 129 |
+
return _DTYPE_NAMES[X.dtype], shape, _tensor_bytes(X)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _decode_tensor(dtype_name: str, shape_json: str, data: bytes) -> Tensor:
|
| 133 |
+
try:
|
| 134 |
+
dtype = _NAME_DTYPES[dtype_name]
|
| 135 |
+
except KeyError as error:
|
| 136 |
+
raise ValueError(f"Unsupported stored dtype {dtype_name!r}.") from error
|
| 137 |
+
shape = tuple(json.loads(shape_json))
|
| 138 |
+
# uint8 is used only as a byte-level carrier, preserving BF16 bits exactly.
|
| 139 |
+
byte_array = np.frombuffer(data, dtype=np.uint8).copy()
|
| 140 |
+
X = torch.from_numpy(byte_array).view(dtype)
|
| 141 |
+
return X.reshape(shape).clone()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _index_path(path: str | Path) -> Path:
|
| 145 |
+
path = Path(path)
|
| 146 |
+
if path.suffix == ".json":
|
| 147 |
+
return path
|
| 148 |
+
if path.suffix == ".safetensors":
|
| 149 |
+
return path.with_suffix(".json")
|
| 150 |
+
return path / "index.json"
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _run_manifest_path(path: str | Path) -> Path:
|
| 154 |
+
path = Path(path)
|
| 155 |
+
if path.name == "index.json":
|
| 156 |
+
return path.with_name("run.json")
|
| 157 |
+
if path.suffix == ".json":
|
| 158 |
+
return path.with_name(f"{path.stem}.run.json")
|
| 159 |
+
if path.suffix == ".safetensors":
|
| 160 |
+
return path.with_suffix(".run.json")
|
| 161 |
+
return path / "run.json"
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _resolve_index_child(root: Path, relative: str, *, label: str) -> Path:
|
| 165 |
+
relative_path = Path(relative)
|
| 166 |
+
candidate = (root / relative_path).resolve()
|
| 167 |
+
if relative_path.is_absolute() or candidate.parent != root.resolve():
|
| 168 |
+
raise ValueError(f"Safetensors {label} references a file outside its output directory.")
|
| 169 |
+
return candidate
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _canonical_json_bytes(payload: dict[str, Any]) -> bytes:
|
| 173 |
+
return (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _load_authoritative_index(
|
| 177 |
+
path: str | Path,
|
| 178 |
+
) -> tuple[dict[str, Any], Path, dict[str, Any]]:
|
| 179 |
+
"""Load the index selected by the atomic run-manifest commit record."""
|
| 180 |
+
|
| 181 |
+
stable_index_path = _index_path(path)
|
| 182 |
+
run_manifest_path = _run_manifest_path(path)
|
| 183 |
+
if not run_manifest_path.is_file():
|
| 184 |
+
raise ValueError(f"Missing safetensors run manifest: {run_manifest_path}.")
|
| 185 |
+
run_manifest = json.loads(run_manifest_path.read_text(encoding="utf-8"))
|
| 186 |
+
if not isinstance(run_manifest, dict):
|
| 187 |
+
raise ValueError("Safetensors run manifest must contain a JSON object.")
|
| 188 |
+
if run_manifest.get("format") != "fastplms-embedding-run":
|
| 189 |
+
raise ValueError(f"Not a FastPLMs embedding run manifest: {run_manifest_path}.")
|
| 190 |
+
version = run_manifest.get("version")
|
| 191 |
+
index_reference = run_manifest.get("index")
|
| 192 |
+
if not isinstance(index_reference, dict):
|
| 193 |
+
raise ValueError("Safetensors run manifest contains an invalid index reference.")
|
| 194 |
+
if version == 1:
|
| 195 |
+
snapshot = run_manifest.get("index_payload")
|
| 196 |
+
if isinstance(snapshot, dict):
|
| 197 |
+
payload = snapshot
|
| 198 |
+
index_bytes = _canonical_json_bytes(payload)
|
| 199 |
+
elif snapshot is None:
|
| 200 |
+
index_bytes = stable_index_path.read_bytes()
|
| 201 |
+
payload = json.loads(index_bytes.decode("utf-8"))
|
| 202 |
+
if not isinstance(payload, dict):
|
| 203 |
+
raise ValueError("Safetensors index must contain a JSON object.")
|
| 204 |
+
else:
|
| 205 |
+
raise ValueError("Safetensors run manifest contains an invalid index snapshot.")
|
| 206 |
+
expected = {
|
| 207 |
+
"file": stable_index_path.name,
|
| 208 |
+
"sha256": hashlib.sha256(index_bytes).hexdigest(),
|
| 209 |
+
}
|
| 210 |
+
index_path = stable_index_path
|
| 211 |
+
elif version == 2:
|
| 212 |
+
relative = index_reference.get("file")
|
| 213 |
+
if not isinstance(relative, str):
|
| 214 |
+
raise ValueError("Safetensors run manifest index file is invalid.")
|
| 215 |
+
index_path = _resolve_index_child(stable_index_path.parent, relative, label="run manifest")
|
| 216 |
+
index_bytes = index_path.read_bytes()
|
| 217 |
+
payload = json.loads(index_bytes.decode("utf-8"))
|
| 218 |
+
if not isinstance(payload, dict):
|
| 219 |
+
raise ValueError("Safetensors generation index must contain a JSON object.")
|
| 220 |
+
if payload.get("version") != 2:
|
| 221 |
+
raise ValueError("Safetensors v2 run manifest must reference a v2 generation index.")
|
| 222 |
+
expected = {
|
| 223 |
+
"file": relative,
|
| 224 |
+
"sha256": hashlib.sha256(index_bytes).hexdigest(),
|
| 225 |
+
}
|
| 226 |
+
else:
|
| 227 |
+
raise ValueError(f"Unsupported safetensors run manifest version {version!r}.")
|
| 228 |
+
if index_reference != expected:
|
| 229 |
+
raise ValueError("Safetensors run manifest does not match its index.")
|
| 230 |
+
if payload.get("format") != "fastplms-embedding-safetensors":
|
| 231 |
+
raise ValueError(f"Not a FastPLMs embedding index: {index_path}.")
|
| 232 |
+
record_count = payload.get("record_count")
|
| 233 |
+
if record_count is None:
|
| 234 |
+
legacy_records = payload.get("records", ())
|
| 235 |
+
if not isinstance(legacy_records, list):
|
| 236 |
+
raise ValueError("Safetensors index contains invalid records.")
|
| 237 |
+
record_count = len(legacy_records)
|
| 238 |
+
if not isinstance(record_count, int) or isinstance(record_count, bool) or record_count < 0:
|
| 239 |
+
raise ValueError("Safetensors record count must be a non-negative integer.")
|
| 240 |
+
if run_manifest.get("record_count") != record_count:
|
| 241 |
+
raise ValueError("Safetensors run manifest record count does not match its index.")
|
| 242 |
+
metadata = payload.get("metadata", {})
|
| 243 |
+
if not isinstance(metadata, dict):
|
| 244 |
+
raise ValueError("Safetensors index metadata must contain a JSON object.")
|
| 245 |
+
if metadata.get("record_count", record_count) != record_count:
|
| 246 |
+
raise ValueError("Safetensors metadata record count does not match its index.")
|
| 247 |
+
if version == 1 and run_manifest.get("metadata") != payload.get("metadata"):
|
| 248 |
+
raise ValueError("Safetensors run manifest metadata does not match its index.")
|
| 249 |
+
return payload, index_path, run_manifest
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def safetensors_result_exists(path: str | Path) -> bool:
|
| 253 |
+
"""Return whether an authoritative committed safetensors run exists."""
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
_load_authoritative_index(path)
|
| 257 |
+
except (OSError, ValueError, json.JSONDecodeError):
|
| 258 |
+
return False
|
| 259 |
+
return True
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _load_safetensor(path: Path, key: str) -> Tensor:
|
| 263 |
+
try:
|
| 264 |
+
from safetensors import safe_open
|
| 265 |
+
except ImportError as error:
|
| 266 |
+
raise ImportError("Loading embeddings requires the 'safetensors' package.") from error
|
| 267 |
+
with safe_open(path, framework="pt", device="cpu") as handle:
|
| 268 |
+
return cast(Tensor, handle.get_tensor(key))
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _safetensors_shard_prefix(path: str | Path) -> str:
|
| 272 |
+
requested_path = Path(path)
|
| 273 |
+
if requested_path.suffix in {".json", ".safetensors"}:
|
| 274 |
+
return f"{requested_path.stem}-embeddings"
|
| 275 |
+
return "embeddings"
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _authoritative_index_payload(path: str | Path) -> dict[str, Any] | None:
|
| 279 |
+
"""Return the last atomically committed generation index when available."""
|
| 280 |
+
|
| 281 |
+
try:
|
| 282 |
+
payload, _, _ = _load_authoritative_index(path)
|
| 283 |
+
except (OSError, ValueError, json.JSONDecodeError):
|
| 284 |
+
return None
|
| 285 |
+
return payload
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _referenced_shards(
|
| 289 |
+
index_path: Path,
|
| 290 |
+
payload: dict[str, Any] | None = None,
|
| 291 |
+
) -> set[Path]:
|
| 292 |
+
if payload is None:
|
| 293 |
+
payload = _authoritative_index_payload(index_path)
|
| 294 |
+
if payload is None:
|
| 295 |
+
return set()
|
| 296 |
+
shards: set[Path] = set()
|
| 297 |
+
for descriptor_shard in payload.get("descriptor_shards", ()):
|
| 298 |
+
tensor_file = descriptor_shard.get("tensor_file")
|
| 299 |
+
if isinstance(tensor_file, str):
|
| 300 |
+
candidate = _resolve_index_child(
|
| 301 |
+
index_path.parent, tensor_file, label="descriptor index"
|
| 302 |
+
)
|
| 303 |
+
shards.add(candidate)
|
| 304 |
+
for item in payload.get("records", ()):
|
| 305 |
+
relative = item.get("tensor", {}).get("file")
|
| 306 |
+
if not isinstance(relative, str):
|
| 307 |
+
continue
|
| 308 |
+
candidate = (index_path.parent / relative).resolve()
|
| 309 |
+
if candidate.parent == index_path.parent.resolve():
|
| 310 |
+
shards.add(candidate)
|
| 311 |
+
return shards
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _validate_tensor_descriptor(
|
| 315 |
+
tensor: dict[str, Any],
|
| 316 |
+
) -> tuple[str, str, tuple[int, ...], str]:
|
| 317 |
+
key = tensor.get("key")
|
| 318 |
+
if not isinstance(key, str) or not key:
|
| 319 |
+
raise ValueError("Safetensors descriptor tensor key is invalid.")
|
| 320 |
+
dtype = tensor.get("dtype")
|
| 321 |
+
if not isinstance(dtype, str) or dtype not in _NAME_DTYPES:
|
| 322 |
+
raise ValueError("Safetensors descriptor tensor dtype is invalid.")
|
| 323 |
+
raw_shape = tensor.get("shape")
|
| 324 |
+
if not isinstance(raw_shape, (list, tuple)) or not all(
|
| 325 |
+
isinstance(dimension, int) and not isinstance(dimension, bool) and dimension >= 0
|
| 326 |
+
for dimension in raw_shape
|
| 327 |
+
):
|
| 328 |
+
raise ValueError("Safetensors descriptor tensor shape is invalid.")
|
| 329 |
+
sha256 = tensor.get("sha256")
|
| 330 |
+
if (
|
| 331 |
+
not isinstance(sha256, str)
|
| 332 |
+
or len(sha256) != 64
|
| 333 |
+
or sha256 != sha256.lower()
|
| 334 |
+
or any(character not in "0123456789abcdef" for character in sha256)
|
| 335 |
+
):
|
| 336 |
+
raise ValueError("Safetensors descriptor tensor SHA-256 is invalid.")
|
| 337 |
+
return key, dtype, tuple(raw_shape), sha256
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def _record_from_safetensors_descriptor(root: Path, item: dict[str, Any]) -> EmbeddingRecord:
|
| 341 |
+
if not isinstance(item, dict):
|
| 342 |
+
raise ValueError("Safetensors record descriptor must contain a JSON object.")
|
| 343 |
+
record_id = item.get("id")
|
| 344 |
+
sequence = item.get("sequence")
|
| 345 |
+
if not isinstance(record_id, str) or not record_id:
|
| 346 |
+
raise ValueError("Safetensors descriptor record ID is invalid.")
|
| 347 |
+
if not isinstance(sequence, str) or not sequence:
|
| 348 |
+
raise ValueError("Safetensors descriptor sequence is invalid.")
|
| 349 |
+
tensor = item.get("tensor")
|
| 350 |
+
if not isinstance(tensor, dict):
|
| 351 |
+
raise ValueError("Safetensors descriptor is missing tensor metadata.")
|
| 352 |
+
relative = tensor.get("file")
|
| 353 |
+
if not isinstance(relative, str) or not relative:
|
| 354 |
+
raise ValueError("Safetensors descriptor tensor file is invalid.")
|
| 355 |
+
key, dtype, shape, sha256 = _validate_tensor_descriptor(tensor)
|
| 356 |
+
tensor_path = _resolve_index_child(root, relative, label="descriptor")
|
| 357 |
+
if not tensor_path.is_file():
|
| 358 |
+
raise ValueError(f"Safetensors tensor shard is missing: {relative}.")
|
| 359 |
+
|
| 360 |
+
def load_tensor() -> Tensor:
|
| 361 |
+
return _load_safetensor(tensor_path, key)
|
| 362 |
+
|
| 363 |
+
reference = LazyTensorReference(
|
| 364 |
+
source=str(tensor_path),
|
| 365 |
+
key=key,
|
| 366 |
+
dtype=dtype,
|
| 367 |
+
shape=shape,
|
| 368 |
+
sha256=sha256,
|
| 369 |
+
_loader=load_tensor,
|
| 370 |
+
)
|
| 371 |
+
return EmbeddingRecord(record_id, sequence, reference)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class _SafetensorsRecordSequence(Sequence[EmbeddingRecord]):
|
| 375 |
+
"""Lazy immutable view over bounded descriptor JSONL shards."""
|
| 376 |
+
|
| 377 |
+
_fastplms_immutable_sequence = True
|
| 378 |
+
|
| 379 |
+
def __init__(self, root: Path, descriptor_shards: Sequence[dict[str, Any]]) -> None:
|
| 380 |
+
if not isinstance(descriptor_shards, (list, tuple)):
|
| 381 |
+
raise ValueError("Safetensors generation index has invalid descriptor shards.")
|
| 382 |
+
self.root = root
|
| 383 |
+
self.shards = tuple(descriptor_shards)
|
| 384 |
+
cumulative: list[int] = []
|
| 385 |
+
total = 0
|
| 386 |
+
for shard in self.shards:
|
| 387 |
+
if not isinstance(shard, dict):
|
| 388 |
+
raise ValueError("Safetensors descriptor shard entry is invalid.")
|
| 389 |
+
relative = shard.get("file")
|
| 390 |
+
declared_count = shard.get("count")
|
| 391 |
+
if (
|
| 392 |
+
not isinstance(declared_count, int)
|
| 393 |
+
or isinstance(declared_count, bool)
|
| 394 |
+
or declared_count < 0
|
| 395 |
+
):
|
| 396 |
+
raise ValueError("Safetensors descriptor shard count is invalid.")
|
| 397 |
+
declared_sha256 = shard.get("sha256")
|
| 398 |
+
if not isinstance(declared_sha256, str) or len(declared_sha256) != 64:
|
| 399 |
+
raise ValueError("Safetensors descriptor shard SHA-256 is invalid.")
|
| 400 |
+
if not isinstance(relative, str):
|
| 401 |
+
raise ValueError("Safetensors descriptor index file is invalid.")
|
| 402 |
+
descriptor_path = _resolve_index_child(root, relative, label="index")
|
| 403 |
+
tensor_file = shard.get("tensor_file")
|
| 404 |
+
if not isinstance(tensor_file, str):
|
| 405 |
+
raise ValueError("Safetensors descriptor tensor file is invalid.")
|
| 406 |
+
tensor_path = _resolve_index_child(root, tensor_file, label="index")
|
| 407 |
+
if not tensor_path.is_file():
|
| 408 |
+
raise ValueError(f"Safetensors tensor shard is missing: {tensor_file}.")
|
| 409 |
+
digest = hashlib.sha256()
|
| 410 |
+
count = 0
|
| 411 |
+
with descriptor_path.open("rb") as handle:
|
| 412 |
+
for line in handle:
|
| 413 |
+
digest.update(line)
|
| 414 |
+
if line.strip():
|
| 415 |
+
item = json.loads(line)
|
| 416 |
+
if not isinstance(item, dict):
|
| 417 |
+
raise ValueError("Safetensors record descriptor must be a JSON object.")
|
| 418 |
+
item_tensor = item.get("tensor")
|
| 419 |
+
if not isinstance(item_tensor, dict):
|
| 420 |
+
raise ValueError("Safetensors descriptor is missing tensor metadata.")
|
| 421 |
+
item_tensor_file = item_tensor.get("file")
|
| 422 |
+
if not isinstance(item_tensor_file, str):
|
| 423 |
+
raise ValueError("Safetensors descriptor tensor file is invalid.")
|
| 424 |
+
_resolve_index_child(root, item_tensor_file, label="descriptor")
|
| 425 |
+
if item_tensor_file != tensor_file:
|
| 426 |
+
raise ValueError(
|
| 427 |
+
"Safetensors descriptor tensor file does not match its shard."
|
| 428 |
+
)
|
| 429 |
+
count += 1
|
| 430 |
+
_validate_tensor_descriptor(item_tensor)
|
| 431 |
+
if digest.hexdigest() != declared_sha256 or count != declared_count:
|
| 432 |
+
raise ValueError(
|
| 433 |
+
f"Safetensors descriptor shard failed integrity validation: {relative}."
|
| 434 |
+
)
|
| 435 |
+
total += count
|
| 436 |
+
cumulative.append(total)
|
| 437 |
+
self._cumulative = tuple(cumulative)
|
| 438 |
+
self._count = total
|
| 439 |
+
|
| 440 |
+
def __len__(self) -> int:
|
| 441 |
+
return self._count
|
| 442 |
+
|
| 443 |
+
def _iter_shard(self, shard_index: int) -> Iterator[EmbeddingRecord]:
|
| 444 |
+
descriptor_path = _resolve_index_child(
|
| 445 |
+
self.root, str(self.shards[shard_index]["file"]), label="index"
|
| 446 |
+
)
|
| 447 |
+
with descriptor_path.open("r", encoding="utf-8") as handle:
|
| 448 |
+
for line in handle:
|
| 449 |
+
if line.strip():
|
| 450 |
+
yield _record_from_safetensors_descriptor(self.root, json.loads(line))
|
| 451 |
+
|
| 452 |
+
def __iter__(self) -> Iterator[EmbeddingRecord]:
|
| 453 |
+
for shard_index in range(len(self.shards)):
|
| 454 |
+
yield from self._iter_shard(shard_index)
|
| 455 |
+
|
| 456 |
+
@overload
|
| 457 |
+
def __getitem__(self, index: int, /) -> EmbeddingRecord: ...
|
| 458 |
+
|
| 459 |
+
@overload
|
| 460 |
+
def __getitem__(self, index: slice, /) -> Sequence[EmbeddingRecord]: ...
|
| 461 |
+
|
| 462 |
+
def __getitem__(self, index: int | slice) -> EmbeddingRecord | Sequence[EmbeddingRecord]:
|
| 463 |
+
if isinstance(index, slice):
|
| 464 |
+
start, stop, step = index.indices(self._count)
|
| 465 |
+
return [self[position] for position in range(start, stop, step)]
|
| 466 |
+
position = index + self._count if index < 0 else index
|
| 467 |
+
if position < 0 or position >= self._count:
|
| 468 |
+
raise IndexError(index)
|
| 469 |
+
shard_index = bisect_right(self._cumulative, position)
|
| 470 |
+
previous = self._cumulative[shard_index - 1] if shard_index else 0
|
| 471 |
+
local_position = position - previous
|
| 472 |
+
for offset, record in enumerate(self._iter_shard(shard_index)):
|
| 473 |
+
if offset == local_position:
|
| 474 |
+
return record
|
| 475 |
+
raise IndexError(index)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class SafetensorsStreamWriter:
|
| 479 |
+
"""Bounded-memory, resumable publisher with immutable retained generations."""
|
| 480 |
+
|
| 481 |
+
def __init__(
|
| 482 |
+
self,
|
| 483 |
+
path: str | Path,
|
| 484 |
+
metadata: dict[str, Any],
|
| 485 |
+
*,
|
| 486 |
+
shard_size: int = DEFAULT_SHARD_SIZE,
|
| 487 |
+
existing: Iterable[EmbeddingRecord] = (),
|
| 488 |
+
reuse_existing: bool = False,
|
| 489 |
+
publish_initial: bool = True,
|
| 490 |
+
publish_incremental: bool = True,
|
| 491 |
+
) -> None:
|
| 492 |
+
try:
|
| 493 |
+
from safetensors.torch import save_file
|
| 494 |
+
except ImportError as error:
|
| 495 |
+
raise ImportError("Saving embeddings requires the 'safetensors' package.") from error
|
| 496 |
+
if shard_size <= 0:
|
| 497 |
+
raise ValueError("shard_size must be positive.")
|
| 498 |
+
|
| 499 |
+
self.path = Path(path)
|
| 500 |
+
self.index_path = _index_path(path)
|
| 501 |
+
self.run_manifest_path = _run_manifest_path(path)
|
| 502 |
+
self.index_path.parent.mkdir(parents=True, exist_ok=True)
|
| 503 |
+
self.metadata = _persistent_metadata(
|
| 504 |
+
metadata,
|
| 505 |
+
descriptor_index="safetensors-generation-index",
|
| 506 |
+
record_count=0,
|
| 507 |
+
)
|
| 508 |
+
self.shard_size = shard_size
|
| 509 |
+
self.publish_incremental = publish_incremental
|
| 510 |
+
self._save_file = save_file
|
| 511 |
+
authoritative_payload = _authoritative_index_payload(path)
|
| 512 |
+
prefix = _safetensors_shard_prefix(path)
|
| 513 |
+
# A random generation identity prevents a new writer from reusing a
|
| 514 |
+
# previously published or interrupted generation name. Published files
|
| 515 |
+
# are immutable and remain available to lazy readers until explicit GC.
|
| 516 |
+
self._generation = uuid4().hex
|
| 517 |
+
self._prefix = prefix
|
| 518 |
+
self._shard_index = 0
|
| 519 |
+
self._seed_index = 0
|
| 520 |
+
self._commit_index = 0
|
| 521 |
+
self._descriptor_shards: list[dict[str, Any]] = []
|
| 522 |
+
self._record_count = 0
|
| 523 |
+
self._current: dict[str, Tensor] = {}
|
| 524 |
+
self._pending: list[tuple[EmbeddingRecord, str, str, tuple[int, ...], str]] = []
|
| 525 |
+
self._current_size = 0
|
| 526 |
+
if reuse_existing:
|
| 527 |
+
if authoritative_payload is None:
|
| 528 |
+
raise ValueError("Cannot resume without an authoritative safetensors index.")
|
| 529 |
+
authoritative_metadata = authoritative_payload.get("metadata")
|
| 530 |
+
if not isinstance(authoritative_metadata, dict) or authoritative_metadata.get(
|
| 531 |
+
"run_fingerprint"
|
| 532 |
+
) != self.metadata.get("run_fingerprint"):
|
| 533 |
+
raise ValueError("Cannot resume a safetensors run with a different fingerprint.")
|
| 534 |
+
expected_prefix_length = (
|
| 535 |
+
len(existing) if isinstance(existing, Sequence) else sum(1 for _ in existing)
|
| 536 |
+
)
|
| 537 |
+
if authoritative_payload.get("version") == 2:
|
| 538 |
+
self._descriptor_shards = list(authoritative_payload.get("descriptor_shards", ()))
|
| 539 |
+
self._record_count = int(authoritative_payload.get("record_count", 0))
|
| 540 |
+
else:
|
| 541 |
+
legacy_records = list(authoritative_payload.get("records", ()))
|
| 542 |
+
self._record_count = len(legacy_records)
|
| 543 |
+
if legacy_records:
|
| 544 |
+
self._descriptor_shards.extend(self._write_descriptor_seed(legacy_records))
|
| 545 |
+
if expected_prefix_length != self._record_count:
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"The resumable safetensors prefix does not match the validated "
|
| 548 |
+
"embedding records."
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
if publish_initial:
|
| 552 |
+
self._publish_metadata(complete=False)
|
| 553 |
+
|
| 554 |
+
def _write_descriptor_file(
|
| 555 |
+
self,
|
| 556 |
+
name: str,
|
| 557 |
+
descriptors: Sequence[dict[str, Any]],
|
| 558 |
+
*,
|
| 559 |
+
tensor_file: str,
|
| 560 |
+
) -> dict[str, Any]:
|
| 561 |
+
temporary = self.index_path.parent / f".{name}.tmp"
|
| 562 |
+
destination = self.index_path.parent / name
|
| 563 |
+
if temporary.exists() or destination.exists():
|
| 564 |
+
raise FileExistsError(
|
| 565 |
+
f"Refusing to reuse immutable safetensors generation path {destination}."
|
| 566 |
+
)
|
| 567 |
+
digest = hashlib.sha256()
|
| 568 |
+
with temporary.open("wb") as handle:
|
| 569 |
+
for item in descriptors:
|
| 570 |
+
encoded = (
|
| 571 |
+
json.dumps(item, sort_keys=True, separators=(",", ":")).encode("utf-8") + b"\n"
|
| 572 |
+
)
|
| 573 |
+
handle.write(encoded)
|
| 574 |
+
digest.update(encoded)
|
| 575 |
+
temporary.replace(destination)
|
| 576 |
+
return {
|
| 577 |
+
"file": name,
|
| 578 |
+
"sha256": digest.hexdigest(),
|
| 579 |
+
"count": len(descriptors),
|
| 580 |
+
"tensor_file": tensor_file,
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
def _write_descriptor_seed(self, records: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 584 |
+
groups: list[tuple[str, list[dict[str, Any]]]] = []
|
| 585 |
+
for record in records:
|
| 586 |
+
tensor_file = str(record["tensor"]["file"])
|
| 587 |
+
if (
|
| 588 |
+
not groups
|
| 589 |
+
or groups[-1][0] != tensor_file
|
| 590 |
+
or len(groups[-1][1]) == _MAX_RECORDS_PER_DESCRIPTOR_SHARD
|
| 591 |
+
):
|
| 592 |
+
groups.append((tensor_file, []))
|
| 593 |
+
groups[-1][1].append(record)
|
| 594 |
+
descriptor_shards: list[dict[str, Any]] = []
|
| 595 |
+
for tensor_file, descriptors in groups:
|
| 596 |
+
self._seed_index += 1
|
| 597 |
+
name = (
|
| 598 |
+
f"{self._prefix}-records-run-{self._generation}-seed-{self._seed_index:05d}.jsonl"
|
| 599 |
+
)
|
| 600 |
+
descriptor_shards.append(
|
| 601 |
+
self._write_descriptor_file(name, descriptors, tensor_file=tensor_file)
|
| 602 |
+
)
|
| 603 |
+
return descriptor_shards
|
| 604 |
+
|
| 605 |
+
def _write_shard(self) -> None:
|
| 606 |
+
if not self._current:
|
| 607 |
+
return
|
| 608 |
+
self._shard_index += 1
|
| 609 |
+
name = f"{self._prefix}-run-{self._generation}-{self._shard_index:05d}.safetensors"
|
| 610 |
+
temporary = self.index_path.parent / f".{name}.tmp"
|
| 611 |
+
destination = self.index_path.parent / name
|
| 612 |
+
if temporary.exists() or destination.exists():
|
| 613 |
+
raise FileExistsError(
|
| 614 |
+
f"Refusing to reuse immutable safetensors generation path {destination}."
|
| 615 |
+
)
|
| 616 |
+
self._save_file(self._current, temporary)
|
| 617 |
+
temporary.replace(destination)
|
| 618 |
+
descriptors: list[dict[str, Any]] = []
|
| 619 |
+
for record, key, dtype_name, shape, digest in self._pending:
|
| 620 |
+
descriptors.append(
|
| 621 |
+
{
|
| 622 |
+
"id": record.id,
|
| 623 |
+
"sequence": record.sequence,
|
| 624 |
+
"tensor": {
|
| 625 |
+
"file": name,
|
| 626 |
+
"key": key,
|
| 627 |
+
"dtype": dtype_name,
|
| 628 |
+
"shape": list(shape),
|
| 629 |
+
"sha256": digest,
|
| 630 |
+
},
|
| 631 |
+
}
|
| 632 |
+
)
|
| 633 |
+
descriptor_name = (
|
| 634 |
+
f"{self._prefix}-records-run-{self._generation}-{self._shard_index:05d}.jsonl"
|
| 635 |
+
)
|
| 636 |
+
self._descriptor_shards.append(
|
| 637 |
+
self._write_descriptor_file(descriptor_name, descriptors, tensor_file=name)
|
| 638 |
+
)
|
| 639 |
+
self._record_count += len(descriptors)
|
| 640 |
+
self._current = {}
|
| 641 |
+
self._pending = []
|
| 642 |
+
self._current_size = 0
|
| 643 |
+
|
| 644 |
+
def append(
|
| 645 |
+
self,
|
| 646 |
+
records: Iterable[EmbeddingRecord],
|
| 647 |
+
*,
|
| 648 |
+
publish: bool | None = None,
|
| 649 |
+
) -> None:
|
| 650 |
+
"""Persist records while retaining at most one shard of tensors."""
|
| 651 |
+
|
| 652 |
+
for record in records:
|
| 653 |
+
position = self._record_count + len(self._pending)
|
| 654 |
+
tensor = record.load_tensor().detach().cpu().contiguous()
|
| 655 |
+
if tensor.dtype not in _DTYPE_NAMES:
|
| 656 |
+
raise TypeError(f"Unsupported tensor dtype {tensor.dtype}.")
|
| 657 |
+
nbytes = tensor.numel() * tensor.element_size()
|
| 658 |
+
if nbytes > self.shard_size:
|
| 659 |
+
raise ValueError(
|
| 660 |
+
f"Embedding {position} requires {nbytes} bytes and cannot fit in a "
|
| 661 |
+
f"{self.shard_size}-byte safetensors shard."
|
| 662 |
+
)
|
| 663 |
+
if self._current and (
|
| 664 |
+
self._current_size + nbytes > self.shard_size
|
| 665 |
+
or len(self._pending) == _MAX_RECORDS_PER_DESCRIPTOR_SHARD
|
| 666 |
+
):
|
| 667 |
+
self._write_shard()
|
| 668 |
+
if self.publish_incremental:
|
| 669 |
+
self._publish_metadata(complete=False)
|
| 670 |
+
position = self._record_count
|
| 671 |
+
key = f"embedding_{position:08d}"
|
| 672 |
+
self._current[key] = tensor
|
| 673 |
+
self._current_size += nbytes
|
| 674 |
+
self._pending.append(
|
| 675 |
+
(
|
| 676 |
+
record,
|
| 677 |
+
key,
|
| 678 |
+
_DTYPE_NAMES[tensor.dtype],
|
| 679 |
+
tuple(tensor.shape),
|
| 680 |
+
tensor_sha256(tensor),
|
| 681 |
+
)
|
| 682 |
+
)
|
| 683 |
+
if publish:
|
| 684 |
+
self.publish(complete=False)
|
| 685 |
+
|
| 686 |
+
def _publish_metadata(
|
| 687 |
+
self,
|
| 688 |
+
*,
|
| 689 |
+
complete: bool,
|
| 690 |
+
metadata: dict[str, Any] | None = None,
|
| 691 |
+
) -> EmbeddingResult:
|
| 692 |
+
"""Atomically expose one self-consistent metadata generation."""
|
| 693 |
+
|
| 694 |
+
if metadata is not None:
|
| 695 |
+
self.metadata = _persistent_metadata(
|
| 696 |
+
metadata,
|
| 697 |
+
descriptor_index="safetensors-generation-index",
|
| 698 |
+
)
|
| 699 |
+
self.metadata["complete"] = complete
|
| 700 |
+
self.metadata["record_count"] = self._record_count
|
| 701 |
+
self._commit_index += 1
|
| 702 |
+
payload = {
|
| 703 |
+
"version": 2,
|
| 704 |
+
"format": "fastplms-embedding-safetensors",
|
| 705 |
+
"metadata": self.metadata,
|
| 706 |
+
"record_count": self._record_count,
|
| 707 |
+
"descriptor_shards": self._descriptor_shards,
|
| 708 |
+
}
|
| 709 |
+
generation_index_name = (
|
| 710 |
+
f"{self._prefix}-index-run-{self._generation}-{self._commit_index:05d}.json"
|
| 711 |
+
)
|
| 712 |
+
generation_index_path = self.index_path.parent / generation_index_name
|
| 713 |
+
temporary_generation_index = generation_index_path.with_name(
|
| 714 |
+
f".{generation_index_path.name}.tmp"
|
| 715 |
+
)
|
| 716 |
+
if temporary_generation_index.exists() or generation_index_path.exists():
|
| 717 |
+
raise FileExistsError(
|
| 718 |
+
f"Refusing to reuse immutable safetensors generation index {generation_index_path}."
|
| 719 |
+
)
|
| 720 |
+
encoded_index = _canonical_json_bytes(payload)
|
| 721 |
+
temporary_generation_index.write_bytes(encoded_index)
|
| 722 |
+
temporary_generation_index.replace(generation_index_path)
|
| 723 |
+
|
| 724 |
+
index_sha256 = hashlib.sha256(encoded_index).hexdigest()
|
| 725 |
+
index_reference = {
|
| 726 |
+
"file": generation_index_name,
|
| 727 |
+
"sha256": index_sha256,
|
| 728 |
+
}
|
| 729 |
+
run_manifest = {
|
| 730 |
+
"version": 2,
|
| 731 |
+
"format": "fastplms-embedding-run",
|
| 732 |
+
"index": index_reference,
|
| 733 |
+
"record_count": self._record_count,
|
| 734 |
+
}
|
| 735 |
+
pointer_identity = f"{self._generation}-{self._commit_index:05d}"
|
| 736 |
+
temporary_manifest = self.run_manifest_path.with_name(
|
| 737 |
+
f".{self.run_manifest_path.name}.{pointer_identity}.tmp"
|
| 738 |
+
)
|
| 739 |
+
temporary_manifest.write_bytes(_canonical_json_bytes(run_manifest))
|
| 740 |
+
temporary_manifest.replace(self.run_manifest_path)
|
| 741 |
+
|
| 742 |
+
# ``index.json`` is a non-authoritative convenience pointer. The run
|
| 743 |
+
# manifest is committed first, so interruption here cannot invalidate
|
| 744 |
+
# the newly committed generation.
|
| 745 |
+
stable_pointer = {
|
| 746 |
+
"version": 2,
|
| 747 |
+
"format": "fastplms-embedding-index-pointer",
|
| 748 |
+
"index": index_reference,
|
| 749 |
+
}
|
| 750 |
+
temporary_index = self.index_path.with_name(
|
| 751 |
+
f".{self.index_path.name}.{pointer_identity}.tmp"
|
| 752 |
+
)
|
| 753 |
+
temporary_index.write_bytes(_canonical_json_bytes(stable_pointer))
|
| 754 |
+
temporary_index.replace(self.index_path)
|
| 755 |
+
|
| 756 |
+
return load_safetensors_result(self.index_path)
|
| 757 |
+
|
| 758 |
+
def publish(
|
| 759 |
+
self,
|
| 760 |
+
*,
|
| 761 |
+
complete: bool,
|
| 762 |
+
metadata: dict[str, Any] | None = None,
|
| 763 |
+
) -> EmbeddingResult:
|
| 764 |
+
"""Flush the current shard and atomically expose a consistent generation."""
|
| 765 |
+
|
| 766 |
+
self._write_shard()
|
| 767 |
+
return self._publish_metadata(complete=complete, metadata=metadata)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def save_safetensors_result(
|
| 771 |
+
result: EmbeddingResult,
|
| 772 |
+
path: str | Path,
|
| 773 |
+
*,
|
| 774 |
+
shard_size: int = DEFAULT_SHARD_SIZE,
|
| 775 |
+
) -> EmbeddingResult:
|
| 776 |
+
"""Write sharded safetensors without materializing the full result."""
|
| 777 |
+
|
| 778 |
+
writer = SafetensorsStreamWriter(
|
| 779 |
+
path,
|
| 780 |
+
result.metadata,
|
| 781 |
+
shard_size=shard_size,
|
| 782 |
+
publish_initial=False,
|
| 783 |
+
publish_incremental=False,
|
| 784 |
+
)
|
| 785 |
+
writer.append(result, publish=False)
|
| 786 |
+
return writer.publish(complete=bool(result.metadata.get("complete", True)))
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def load_safetensors_result(path: str | Path) -> EmbeddingResult:
|
| 790 |
+
"""Load an indexed safetensors result without loading tensor payloads."""
|
| 791 |
+
|
| 792 |
+
payload, index_path, _ = _load_authoritative_index(path)
|
| 793 |
+
if payload.get("version") == 2:
|
| 794 |
+
lazy_records = _SafetensorsRecordSequence(
|
| 795 |
+
index_path.parent, payload.get("descriptor_shards", ())
|
| 796 |
+
)
|
| 797 |
+
if len(lazy_records) != payload.get("record_count"):
|
| 798 |
+
raise ValueError("Safetensors descriptor count does not match its generation index.")
|
| 799 |
+
return EmbeddingResult(lazy_records, payload.get("metadata", {}))
|
| 800 |
+
|
| 801 |
+
records: list[EmbeddingRecord] = []
|
| 802 |
+
for item in payload["records"]:
|
| 803 |
+
records.append(_record_from_safetensors_descriptor(index_path.parent, item))
|
| 804 |
+
return EmbeddingResult(records, payload.get("metadata", {}))
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def garbage_collect_safetensors_generations(
|
| 808 |
+
path: str | Path,
|
| 809 |
+
*,
|
| 810 |
+
dry_run: bool = True,
|
| 811 |
+
confirm_no_active_readers_or_writers: bool = False,
|
| 812 |
+
) -> tuple[Path, ...]:
|
| 813 |
+
"""Remove non-authoritative generations after an explicit exclusivity check.
|
| 814 |
+
|
| 815 |
+
Safetensors results retain immutable historical generations because an
|
| 816 |
+
already-open :class:`EmbeddingResult` resolves tensors through those exact
|
| 817 |
+
descriptor and shard paths. Destructive collection is therefore safe only
|
| 818 |
+
when the caller guarantees that no reader or writer for ``path`` remains
|
| 819 |
+
active. ``dry_run=True`` is the default and returns the paths that would be
|
| 820 |
+
removed without changing the output directory.
|
| 821 |
+
"""
|
| 822 |
+
|
| 823 |
+
if not isinstance(dry_run, bool):
|
| 824 |
+
raise TypeError("dry_run must be a bool.")
|
| 825 |
+
if not isinstance(confirm_no_active_readers_or_writers, bool):
|
| 826 |
+
raise TypeError("confirm_no_active_readers_or_writers must be a bool.")
|
| 827 |
+
if not dry_run and not confirm_no_active_readers_or_writers:
|
| 828 |
+
raise ValueError(
|
| 829 |
+
"Destructive safetensors generation collection requires "
|
| 830 |
+
"confirm_no_active_readers_or_writers=True."
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
# Validate the full descriptor graph before identifying anything as stale.
|
| 834 |
+
load_safetensors_result(path)
|
| 835 |
+
payload, authoritative_index_path, _ = _load_authoritative_index(path)
|
| 836 |
+
stable_index_path = _index_path(path)
|
| 837 |
+
run_manifest_path = _run_manifest_path(path)
|
| 838 |
+
root = stable_index_path.parent
|
| 839 |
+
prefix = _safetensors_shard_prefix(path)
|
| 840 |
+
protected = {
|
| 841 |
+
stable_index_path.resolve(),
|
| 842 |
+
run_manifest_path.resolve(),
|
| 843 |
+
authoritative_index_path.resolve(),
|
| 844 |
+
*_referenced_shards(stable_index_path, payload),
|
| 845 |
+
}
|
| 846 |
+
for descriptor_shard in payload.get("descriptor_shards", ()):
|
| 847 |
+
relative = descriptor_shard.get("file")
|
| 848 |
+
if isinstance(relative, str):
|
| 849 |
+
protected.add(_resolve_index_child(root, relative, label="index").resolve())
|
| 850 |
+
|
| 851 |
+
candidates: set[Path] = set()
|
| 852 |
+
for pattern in (
|
| 853 |
+
f"{prefix}-run-*-*.safetensors",
|
| 854 |
+
f"{prefix}-records-run-*.jsonl",
|
| 855 |
+
f"{prefix}-index-run-*.json",
|
| 856 |
+
f".{prefix}-*.tmp",
|
| 857 |
+
):
|
| 858 |
+
candidates.update(root.glob(pattern))
|
| 859 |
+
candidates.update(root.glob(f".{stable_index_path.name}.*.tmp"))
|
| 860 |
+
candidates.update(root.glob(f".{run_manifest_path.name}.*.tmp"))
|
| 861 |
+
|
| 862 |
+
stale = tuple(
|
| 863 |
+
sorted(
|
| 864 |
+
(candidate for candidate in candidates if candidate.resolve() not in protected),
|
| 865 |
+
key=lambda candidate: candidate.name,
|
| 866 |
+
)
|
| 867 |
+
)
|
| 868 |
+
if not dry_run:
|
| 869 |
+
for candidate in stale:
|
| 870 |
+
candidate.unlink(missing_ok=True)
|
| 871 |
+
return stale
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def _ensure_sqlite_schema(connection: sqlite3.Connection) -> None:
|
| 875 |
+
connection.executescript(
|
| 876 |
+
"""
|
| 877 |
+
PRAGMA foreign_keys = ON;
|
| 878 |
+
CREATE TABLE IF NOT EXISTS runs (
|
| 879 |
+
run_id TEXT PRIMARY KEY,
|
| 880 |
+
metadata_json TEXT NOT NULL,
|
| 881 |
+
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 882 |
+
published_order INTEGER
|
| 883 |
+
);
|
| 884 |
+
CREATE TABLE IF NOT EXISTS tensors (
|
| 885 |
+
run_id TEXT NOT NULL,
|
| 886 |
+
position INTEGER NOT NULL,
|
| 887 |
+
dtype TEXT NOT NULL,
|
| 888 |
+
shape_json TEXT NOT NULL,
|
| 889 |
+
data BLOB NOT NULL,
|
| 890 |
+
sha256 TEXT NOT NULL,
|
| 891 |
+
PRIMARY KEY (run_id, position),
|
| 892 |
+
FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE
|
| 893 |
+
);
|
| 894 |
+
CREATE TABLE IF NOT EXISTS records (
|
| 895 |
+
run_id TEXT NOT NULL,
|
| 896 |
+
position INTEGER NOT NULL,
|
| 897 |
+
record_id TEXT NOT NULL,
|
| 898 |
+
sequence TEXT NOT NULL,
|
| 899 |
+
PRIMARY KEY (run_id, position),
|
| 900 |
+
FOREIGN KEY (run_id, position) REFERENCES tensors(run_id, position)
|
| 901 |
+
ON DELETE CASCADE
|
| 902 |
+
);
|
| 903 |
+
"""
|
| 904 |
+
)
|
| 905 |
+
run_columns = {str(row[1]) for row in connection.execute("PRAGMA table_info(runs)").fetchall()}
|
| 906 |
+
if "published_order" not in run_columns:
|
| 907 |
+
connection.execute("ALTER TABLE runs ADD COLUMN published_order INTEGER")
|
| 908 |
+
# Databases created before staged publication exposed every stored run.
|
| 909 |
+
# Preserve that view for historical runs containing committed records.
|
| 910 |
+
connection.execute(
|
| 911 |
+
"UPDATE runs SET published_order = rowid "
|
| 912 |
+
"WHERE published_order IS NULL AND EXISTS ("
|
| 913 |
+
"SELECT 1 FROM records WHERE records.run_id = runs.run_id)"
|
| 914 |
+
)
|
| 915 |
+
connection.execute(
|
| 916 |
+
"CREATE INDEX IF NOT EXISTS runs_published_order_idx ON runs(published_order)"
|
| 917 |
+
)
|
| 918 |
+
if "published_order" not in run_columns:
|
| 919 |
+
# Schema upgrades run before callers open their data transaction.
|
| 920 |
+
# End the migration transaction explicitly so BEGIN IMMEDIATE below
|
| 921 |
+
# remains valid on existing databases.
|
| 922 |
+
connection.commit()
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def save_sqlite_result(result: EmbeddingResult, path: str | Path) -> EmbeddingResult:
|
| 926 |
+
"""Transactionally store an ordered result in normalized SQLite tables."""
|
| 927 |
+
|
| 928 |
+
path = Path(path)
|
| 929 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 930 |
+
run_id = str(result.metadata.get("run_fingerprint", ""))
|
| 931 |
+
if not run_id:
|
| 932 |
+
raise ValueError("SQLite results require metadata['run_fingerprint'].")
|
| 933 |
+
metadata_json = json.dumps(
|
| 934 |
+
_persistent_metadata(
|
| 935 |
+
result.metadata,
|
| 936 |
+
descriptor_index="sqlite-records",
|
| 937 |
+
record_count=len(result),
|
| 938 |
+
),
|
| 939 |
+
sort_keys=True,
|
| 940 |
+
)
|
| 941 |
+
with sqlite3.connect(path, timeout=30) as connection:
|
| 942 |
+
_ensure_sqlite_schema(connection)
|
| 943 |
+
connection.execute("PRAGMA journal_mode = WAL")
|
| 944 |
+
connection.execute("BEGIN IMMEDIATE")
|
| 945 |
+
connection.execute("DELETE FROM runs WHERE run_id = ?", (run_id,))
|
| 946 |
+
connection.execute(
|
| 947 |
+
"INSERT INTO runs(run_id, metadata_json, published_order) "
|
| 948 |
+
"SELECT ?, ?, COALESCE(MAX(published_order), 0) + 1 FROM runs",
|
| 949 |
+
(run_id, metadata_json),
|
| 950 |
+
)
|
| 951 |
+
for position, record in enumerate(result):
|
| 952 |
+
X = record.load_tensor().detach().cpu().contiguous()
|
| 953 |
+
dtype_name, shape_json, data = _encode_tensor(X)
|
| 954 |
+
digest = tensor_sha256(X)
|
| 955 |
+
connection.execute(
|
| 956 |
+
"INSERT INTO tensors VALUES (?, ?, ?, ?, ?, ?)",
|
| 957 |
+
(run_id, position, dtype_name, shape_json, data, digest),
|
| 958 |
+
)
|
| 959 |
+
connection.execute(
|
| 960 |
+
"INSERT INTO records VALUES (?, ?, ?, ?)",
|
| 961 |
+
(run_id, position, record.id, record.sequence),
|
| 962 |
+
)
|
| 963 |
+
connection.commit()
|
| 964 |
+
return load_sqlite_result(path, run_id=run_id)
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
def initialize_sqlite_run(
|
| 968 |
+
path: str | Path,
|
| 969 |
+
metadata: dict[str, Any],
|
| 970 |
+
*,
|
| 971 |
+
resume: bool,
|
| 972 |
+
) -> str:
|
| 973 |
+
"""Create a resumable SQLite run without buffering tensor results."""
|
| 974 |
+
|
| 975 |
+
path = Path(path)
|
| 976 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 977 |
+
run_id = str(metadata.get("run_fingerprint", ""))
|
| 978 |
+
if not run_id:
|
| 979 |
+
raise ValueError("SQLite runs require metadata['run_fingerprint'].")
|
| 980 |
+
with sqlite3.connect(path, timeout=30) as connection:
|
| 981 |
+
_ensure_sqlite_schema(connection)
|
| 982 |
+
connection.execute("PRAGMA journal_mode = WAL")
|
| 983 |
+
connection.execute("BEGIN IMMEDIATE")
|
| 984 |
+
exists = connection.execute("SELECT 1 FROM runs WHERE run_id = ?", (run_id,)).fetchone()
|
| 985 |
+
if exists and not resume:
|
| 986 |
+
connection.execute("DELETE FROM runs WHERE run_id = ?", (run_id,))
|
| 987 |
+
exists = None
|
| 988 |
+
if exists is None:
|
| 989 |
+
initial_metadata = _persistent_metadata(
|
| 990 |
+
metadata,
|
| 991 |
+
descriptor_index="sqlite-records",
|
| 992 |
+
record_count=0,
|
| 993 |
+
)
|
| 994 |
+
connection.execute(
|
| 995 |
+
"INSERT INTO runs(run_id, metadata_json) VALUES (?, ?)",
|
| 996 |
+
(run_id, json.dumps(initial_metadata, sort_keys=True)),
|
| 997 |
+
)
|
| 998 |
+
connection.commit()
|
| 999 |
+
return run_id
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
def append_sqlite_records(
|
| 1003 |
+
path: str | Path,
|
| 1004 |
+
run_id: str,
|
| 1005 |
+
start_position: int,
|
| 1006 |
+
records: list[EmbeddingRecord],
|
| 1007 |
+
*,
|
| 1008 |
+
replace_metadata: dict[str, Any] | None = None,
|
| 1009 |
+
) -> None:
|
| 1010 |
+
"""Commit one ordered embedding batch so an interrupted run can resume."""
|
| 1011 |
+
|
| 1012 |
+
if not isinstance(run_id, str) or not run_id:
|
| 1013 |
+
raise ValueError("run_id must be a non-empty string.")
|
| 1014 |
+
if not isinstance(start_position, int) or isinstance(start_position, bool):
|
| 1015 |
+
raise TypeError("start_position must be a non-negative integer.")
|
| 1016 |
+
if start_position < 0:
|
| 1017 |
+
raise ValueError("start_position must be a non-negative integer.")
|
| 1018 |
+
if not isinstance(records, list) or not all(
|
| 1019 |
+
isinstance(record, EmbeddingRecord) for record in records
|
| 1020 |
+
):
|
| 1021 |
+
raise TypeError("records must be a list of EmbeddingRecord values.")
|
| 1022 |
+
|
| 1023 |
+
with sqlite3.connect(Path(path), timeout=30) as connection:
|
| 1024 |
+
_ensure_sqlite_schema(connection)
|
| 1025 |
+
connection.execute("PRAGMA journal_mode = WAL")
|
| 1026 |
+
connection.execute("BEGIN IMMEDIATE")
|
| 1027 |
+
if replace_metadata is not None:
|
| 1028 |
+
replacement_run_id = str(replace_metadata.get("run_fingerprint", ""))
|
| 1029 |
+
if replacement_run_id != run_id:
|
| 1030 |
+
raise ValueError("Replacement metadata must match the SQLite run ID.")
|
| 1031 |
+
initial_metadata = _persistent_metadata(
|
| 1032 |
+
replace_metadata,
|
| 1033 |
+
descriptor_index="sqlite-records",
|
| 1034 |
+
record_count=0,
|
| 1035 |
+
)
|
| 1036 |
+
connection.execute("DELETE FROM runs WHERE run_id = ?", (run_id,))
|
| 1037 |
+
connection.execute(
|
| 1038 |
+
"INSERT INTO runs(run_id, metadata_json) VALUES (?, ?)",
|
| 1039 |
+
(run_id, json.dumps(initial_metadata, sort_keys=True)),
|
| 1040 |
+
)
|
| 1041 |
+
if connection.execute("SELECT 1 FROM runs WHERE run_id = ?", (run_id,)).fetchone() is None:
|
| 1042 |
+
raise KeyError(f"Missing SQLite embedding run {run_id}.")
|
| 1043 |
+
current_count, minimum_position, maximum_position = connection.execute(
|
| 1044 |
+
"SELECT COUNT(*), MIN(position), MAX(position) FROM records WHERE run_id = ?",
|
| 1045 |
+
(run_id,),
|
| 1046 |
+
).fetchone()
|
| 1047 |
+
if current_count and (minimum_position != 0 or maximum_position != current_count - 1):
|
| 1048 |
+
raise ValueError("SQLite embedding run has a non-contiguous record prefix.")
|
| 1049 |
+
if start_position != current_count:
|
| 1050 |
+
raise ValueError(
|
| 1051 |
+
f"start_position={start_position} does not match the contiguous "
|
| 1052 |
+
f"SQLite prefix length {current_count}."
|
| 1053 |
+
)
|
| 1054 |
+
for offset, record in enumerate(records):
|
| 1055 |
+
position = start_position + offset
|
| 1056 |
+
X = record.load_tensor().detach().cpu().contiguous()
|
| 1057 |
+
dtype_name, shape_json, data = _encode_tensor(X)
|
| 1058 |
+
digest = tensor_sha256(X)
|
| 1059 |
+
connection.execute(
|
| 1060 |
+
"INSERT INTO tensors VALUES (?, ?, ?, ?, ?, ?)",
|
| 1061 |
+
(run_id, position, dtype_name, shape_json, data, digest),
|
| 1062 |
+
)
|
| 1063 |
+
connection.execute(
|
| 1064 |
+
"INSERT INTO records VALUES (?, ?, ?, ?)",
|
| 1065 |
+
(run_id, position, record.id, record.sequence),
|
| 1066 |
+
)
|
| 1067 |
+
row = connection.execute(
|
| 1068 |
+
"SELECT metadata_json FROM runs WHERE run_id = ?", (run_id,)
|
| 1069 |
+
).fetchone()
|
| 1070 |
+
if row is None:
|
| 1071 |
+
raise KeyError(f"Missing SQLite embedding run {run_id}.")
|
| 1072 |
+
metadata = json.loads(row[0])
|
| 1073 |
+
if not isinstance(metadata, dict):
|
| 1074 |
+
raise ValueError("SQLite run metadata must contain a JSON object.")
|
| 1075 |
+
metadata["record_count"] = start_position + len(records)
|
| 1076 |
+
metadata["descriptor_index"] = "sqlite-records"
|
| 1077 |
+
connection.execute(
|
| 1078 |
+
"UPDATE runs SET metadata_json = ? WHERE run_id = ?",
|
| 1079 |
+
(json.dumps(metadata, sort_keys=True), run_id),
|
| 1080 |
+
)
|
| 1081 |
+
if records:
|
| 1082 |
+
connection.execute(
|
| 1083 |
+
"UPDATE runs SET published_order = ("
|
| 1084 |
+
"SELECT COALESCE(MAX(published_order), 0) + 1 FROM runs"
|
| 1085 |
+
") WHERE run_id = ? AND published_order IS NULL",
|
| 1086 |
+
(run_id,),
|
| 1087 |
+
)
|
| 1088 |
+
connection.commit()
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def update_sqlite_run_metadata(path: str | Path, run_id: str, metadata: dict[str, Any]) -> None:
|
| 1092 |
+
"""Finalize reproducibility metadata after the last streamed batch."""
|
| 1093 |
+
|
| 1094 |
+
with sqlite3.connect(Path(path), timeout=30) as connection:
|
| 1095 |
+
row = connection.execute(
|
| 1096 |
+
"SELECT COUNT(*) FROM records WHERE run_id = ?", (run_id,)
|
| 1097 |
+
).fetchone()
|
| 1098 |
+
record_count = int(row[0]) if row is not None else 0
|
| 1099 |
+
cleaned_metadata = _persistent_metadata(
|
| 1100 |
+
metadata,
|
| 1101 |
+
descriptor_index="sqlite-records",
|
| 1102 |
+
record_count=record_count,
|
| 1103 |
+
)
|
| 1104 |
+
updated = connection.execute(
|
| 1105 |
+
"UPDATE runs SET metadata_json = ? WHERE run_id = ?",
|
| 1106 |
+
(json.dumps(cleaned_metadata, sort_keys=True), run_id),
|
| 1107 |
+
).rowcount
|
| 1108 |
+
if updated != 1:
|
| 1109 |
+
raise KeyError(f"Missing SQLite embedding run {run_id}.")
|
| 1110 |
+
connection.commit()
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
def _connect_sqlite_read_only(path: Path) -> sqlite3.Connection:
|
| 1114 |
+
if not path.is_file():
|
| 1115 |
+
raise FileNotFoundError(path)
|
| 1116 |
+
return sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True, timeout=30)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
def _validate_sqlite_result_schema(connection: sqlite3.Connection, path: Path) -> None:
|
| 1120 |
+
tables = {
|
| 1121 |
+
str(row[0])
|
| 1122 |
+
for row in connection.execute(
|
| 1123 |
+
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
| 1124 |
+
).fetchall()
|
| 1125 |
+
}
|
| 1126 |
+
required = {"runs", "records", "tensors"}
|
| 1127 |
+
if not required.issubset(tables):
|
| 1128 |
+
raise ValueError(
|
| 1129 |
+
f"Not a FastPLMs embedding SQLite database: {path}. "
|
| 1130 |
+
"Use convert_legacy_sqlite() for a legacy embeddings table."
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
def _load_sqlite_tensor(path: Path, run_id: str, position: int) -> Tensor:
|
| 1135 |
+
with _connect_sqlite_read_only(path) as connection:
|
| 1136 |
+
row = connection.execute(
|
| 1137 |
+
"SELECT dtype, shape_json, data FROM tensors WHERE run_id = ? AND position = ?",
|
| 1138 |
+
(run_id, position),
|
| 1139 |
+
).fetchone()
|
| 1140 |
+
if row is None:
|
| 1141 |
+
raise KeyError(f"Missing SQLite tensor {run_id}:{position}.")
|
| 1142 |
+
return _decode_tensor(*row)
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def _validate_sqlite_descriptor_row(
|
| 1146 |
+
row: Sequence[Any],
|
| 1147 |
+
) -> tuple[int, str, str, str, str, str]:
|
| 1148 |
+
if len(row) != 6:
|
| 1149 |
+
raise ValueError("SQLite embedding descriptor has an invalid column count.")
|
| 1150 |
+
position, record_id, sequence, dtype_name, shape_json, digest = row
|
| 1151 |
+
if not isinstance(position, int) or isinstance(position, bool) or position < 0:
|
| 1152 |
+
raise ValueError("SQLite embedding position is invalid.")
|
| 1153 |
+
if not isinstance(record_id, str) or not record_id:
|
| 1154 |
+
raise ValueError("SQLite embedding record ID is invalid.")
|
| 1155 |
+
if not isinstance(sequence, str) or not sequence:
|
| 1156 |
+
raise ValueError("SQLite embedding sequence is invalid.")
|
| 1157 |
+
if not isinstance(shape_json, str):
|
| 1158 |
+
raise ValueError("SQLite embedding tensor shape is invalid.")
|
| 1159 |
+
try:
|
| 1160 |
+
shape = json.loads(shape_json)
|
| 1161 |
+
except json.JSONDecodeError as error:
|
| 1162 |
+
raise ValueError("SQLite embedding tensor shape is invalid.") from error
|
| 1163 |
+
_validate_tensor_descriptor(
|
| 1164 |
+
{
|
| 1165 |
+
"key": f"embedding_{position}",
|
| 1166 |
+
"dtype": dtype_name,
|
| 1167 |
+
"shape": shape,
|
| 1168 |
+
"sha256": digest,
|
| 1169 |
+
}
|
| 1170 |
+
)
|
| 1171 |
+
return position, record_id, sequence, dtype_name, shape_json, digest
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def _sqlite_record_from_row(path: Path, run_id: str, row: Sequence[Any]) -> EmbeddingRecord:
|
| 1175 |
+
position, record_id, sequence, dtype_name, shape_json, digest = _validate_sqlite_descriptor_row(
|
| 1176 |
+
row
|
| 1177 |
+
)
|
| 1178 |
+
|
| 1179 |
+
def load_tensor() -> Tensor:
|
| 1180 |
+
return _load_sqlite_tensor(path, run_id, position)
|
| 1181 |
+
|
| 1182 |
+
reference = LazyTensorReference(
|
| 1183 |
+
source=str(path),
|
| 1184 |
+
key=f"{run_id}:{position}",
|
| 1185 |
+
dtype=dtype_name,
|
| 1186 |
+
shape=tuple(json.loads(shape_json)),
|
| 1187 |
+
sha256=digest,
|
| 1188 |
+
_loader=load_tensor,
|
| 1189 |
+
)
|
| 1190 |
+
return EmbeddingRecord(record_id, sequence, reference)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
class _SQLiteRecordSequence(Sequence[EmbeddingRecord]):
|
| 1194 |
+
"""Lazy immutable descriptor view over one SQLite embedding run."""
|
| 1195 |
+
|
| 1196 |
+
_fastplms_immutable_sequence = True
|
| 1197 |
+
|
| 1198 |
+
def __init__(self, path: Path, run_id: str, count: int) -> None:
|
| 1199 |
+
self.path = path
|
| 1200 |
+
self.run_id = run_id
|
| 1201 |
+
self._count = count
|
| 1202 |
+
|
| 1203 |
+
@staticmethod
|
| 1204 |
+
def _row_query() -> str:
|
| 1205 |
+
return (
|
| 1206 |
+
"SELECT r.position, r.record_id, r.sequence, t.dtype, t.shape_json, t.sha256 "
|
| 1207 |
+
"FROM records r JOIN tensors t USING (run_id, position) "
|
| 1208 |
+
"WHERE r.run_id = ?"
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
def __len__(self) -> int:
|
| 1212 |
+
return self._count
|
| 1213 |
+
|
| 1214 |
+
def __iter__(self) -> Iterator[EmbeddingRecord]:
|
| 1215 |
+
with _connect_sqlite_read_only(self.path) as connection:
|
| 1216 |
+
cursor = connection.execute(f"{self._row_query()} ORDER BY r.position", (self.run_id,))
|
| 1217 |
+
while rows := cursor.fetchmany(1_024):
|
| 1218 |
+
for row in rows:
|
| 1219 |
+
yield _sqlite_record_from_row(self.path, self.run_id, row)
|
| 1220 |
+
|
| 1221 |
+
@overload
|
| 1222 |
+
def __getitem__(self, index: int, /) -> EmbeddingRecord: ...
|
| 1223 |
+
|
| 1224 |
+
@overload
|
| 1225 |
+
def __getitem__(self, index: slice, /) -> Sequence[EmbeddingRecord]: ...
|
| 1226 |
+
|
| 1227 |
+
def __getitem__(self, index: int | slice) -> EmbeddingRecord | Sequence[EmbeddingRecord]:
|
| 1228 |
+
if isinstance(index, slice):
|
| 1229 |
+
start, stop, step = index.indices(self._count)
|
| 1230 |
+
return [self[position] for position in range(start, stop, step)]
|
| 1231 |
+
position = index + self._count if index < 0 else index
|
| 1232 |
+
if position < 0 or position >= self._count:
|
| 1233 |
+
raise IndexError(index)
|
| 1234 |
+
with _connect_sqlite_read_only(self.path) as connection:
|
| 1235 |
+
row = connection.execute(
|
| 1236 |
+
f"{self._row_query()} AND r.position = ?",
|
| 1237 |
+
(self.run_id, position),
|
| 1238 |
+
).fetchone()
|
| 1239 |
+
if row is None:
|
| 1240 |
+
raise IndexError(index)
|
| 1241 |
+
return _sqlite_record_from_row(self.path, self.run_id, row)
|
| 1242 |
+
|
| 1243 |
+
|
| 1244 |
+
def load_sqlite_result(
|
| 1245 |
+
path: str | Path,
|
| 1246 |
+
*,
|
| 1247 |
+
run_id: str | None = None,
|
| 1248 |
+
positions: Iterable[int] | None = None,
|
| 1249 |
+
record_ids: Iterable[str] | None = None,
|
| 1250 |
+
sequences: Iterable[str] | None = None,
|
| 1251 |
+
) -> EmbeddingResult:
|
| 1252 |
+
"""Load one SQLite run read-only, optionally in explicit selector order.
|
| 1253 |
+
|
| 1254 |
+
Exactly one selector may be supplied. Repeated selectors are retained. An
|
| 1255 |
+
ID or sequence selector that matches multiple stored rows returns those
|
| 1256 |
+
rows in their original order for every occurrence of that selector.
|
| 1257 |
+
"""
|
| 1258 |
+
|
| 1259 |
+
path = Path(path).resolve()
|
| 1260 |
+
supplied_selectors = sum(
|
| 1261 |
+
selector is not None for selector in (positions, record_ids, sequences)
|
| 1262 |
+
)
|
| 1263 |
+
if supplied_selectors > 1:
|
| 1264 |
+
raise ValueError("Choose at most one of positions, record_ids, or sequences.")
|
| 1265 |
+
normalized_positions = tuple(positions) if positions is not None else None
|
| 1266 |
+
normalized_ids = tuple(record_ids) if record_ids is not None else None
|
| 1267 |
+
normalized_sequences = tuple(sequences) if sequences is not None else None
|
| 1268 |
+
if normalized_positions is not None and not all(
|
| 1269 |
+
isinstance(position, int) and not isinstance(position, bool) and position >= 0
|
| 1270 |
+
for position in normalized_positions
|
| 1271 |
+
):
|
| 1272 |
+
raise ValueError("positions must contain non-negative integers.")
|
| 1273 |
+
for name, values in (
|
| 1274 |
+
("record_ids", normalized_ids),
|
| 1275 |
+
("sequences", normalized_sequences),
|
| 1276 |
+
):
|
| 1277 |
+
if values is not None and not all(isinstance(value, str) for value in values):
|
| 1278 |
+
raise TypeError(f"{name} must contain strings.")
|
| 1279 |
+
|
| 1280 |
+
with _connect_sqlite_read_only(path) as connection:
|
| 1281 |
+
_validate_sqlite_result_schema(connection, path)
|
| 1282 |
+
if run_id is None:
|
| 1283 |
+
run_columns = {
|
| 1284 |
+
str(info[1]) for info in connection.execute("PRAGMA table_info(runs)").fetchall()
|
| 1285 |
+
}
|
| 1286 |
+
if "published_order" in run_columns:
|
| 1287 |
+
row = connection.execute(
|
| 1288 |
+
"SELECT run_id, metadata_json FROM runs "
|
| 1289 |
+
"WHERE published_order IS NOT NULL "
|
| 1290 |
+
"ORDER BY published_order DESC, rowid DESC LIMIT 1"
|
| 1291 |
+
).fetchone()
|
| 1292 |
+
else:
|
| 1293 |
+
row = connection.execute(
|
| 1294 |
+
"SELECT run_id, metadata_json FROM runs "
|
| 1295 |
+
"ORDER BY created_at DESC, rowid DESC LIMIT 1"
|
| 1296 |
+
).fetchone()
|
| 1297 |
+
else:
|
| 1298 |
+
row = connection.execute(
|
| 1299 |
+
"SELECT run_id, metadata_json FROM runs WHERE run_id = ?", (run_id,)
|
| 1300 |
+
).fetchone()
|
| 1301 |
+
if row is None:
|
| 1302 |
+
raise KeyError(f"No embedding run found in {path}.")
|
| 1303 |
+
selected_run, metadata_json = row
|
| 1304 |
+
metadata = json.loads(metadata_json)
|
| 1305 |
+
if not isinstance(metadata, dict):
|
| 1306 |
+
raise ValueError("SQLite run metadata must contain a JSON object.")
|
| 1307 |
+
row_prefix = (
|
| 1308 |
+
"SELECT r.position, r.record_id, r.sequence, t.dtype, t.shape_json, t.sha256 "
|
| 1309 |
+
"FROM records r JOIN tensors t USING (run_id, position) "
|
| 1310 |
+
"WHERE r.run_id = ?"
|
| 1311 |
+
)
|
| 1312 |
+
record_count, minimum_position, maximum_position = connection.execute(
|
| 1313 |
+
"SELECT COUNT(*), MIN(position), MAX(position) FROM records WHERE run_id = ?",
|
| 1314 |
+
(selected_run,),
|
| 1315 |
+
).fetchone()
|
| 1316 |
+
(tensor_count,) = connection.execute(
|
| 1317 |
+
"SELECT COUNT(*) FROM tensors WHERE run_id = ?", (selected_run,)
|
| 1318 |
+
).fetchone()
|
| 1319 |
+
(joined_count,) = connection.execute(
|
| 1320 |
+
"SELECT COUNT(*) FROM records r JOIN tensors t USING (run_id, position) "
|
| 1321 |
+
"WHERE r.run_id = ?",
|
| 1322 |
+
(selected_run,),
|
| 1323 |
+
).fetchone()
|
| 1324 |
+
if (
|
| 1325 |
+
tensor_count != record_count
|
| 1326 |
+
or joined_count != record_count
|
| 1327 |
+
or (record_count and (minimum_position != 0 or maximum_position != record_count - 1))
|
| 1328 |
+
):
|
| 1329 |
+
raise ValueError("SQLite embedding run has inconsistent or non-contiguous records.")
|
| 1330 |
+
metadata_count = metadata.get("record_count")
|
| 1331 |
+
if (
|
| 1332 |
+
not isinstance(metadata_count, int)
|
| 1333 |
+
or isinstance(metadata_count, bool)
|
| 1334 |
+
or metadata_count != record_count
|
| 1335 |
+
):
|
| 1336 |
+
raise ValueError("SQLite metadata record count does not match stored records.")
|
| 1337 |
+
descriptor_cursor = connection.execute(f"{row_prefix} ORDER BY r.position", (selected_run,))
|
| 1338 |
+
while descriptor_rows := descriptor_cursor.fetchmany(1_024):
|
| 1339 |
+
for descriptor_row in descriptor_rows:
|
| 1340 |
+
_validate_sqlite_descriptor_row(descriptor_row)
|
| 1341 |
+
if supplied_selectors == 0:
|
| 1342 |
+
rows: list[tuple[Any, ...]] | None = None
|
| 1343 |
+
else:
|
| 1344 |
+
selector_values: tuple[Any, ...]
|
| 1345 |
+
selector_column: str
|
| 1346 |
+
if normalized_positions is not None:
|
| 1347 |
+
selector_values = normalized_positions
|
| 1348 |
+
selector_column = "r.position"
|
| 1349 |
+
elif normalized_ids is not None:
|
| 1350 |
+
selector_values = normalized_ids
|
| 1351 |
+
selector_column = "r.record_id"
|
| 1352 |
+
else:
|
| 1353 |
+
if normalized_sequences is None:
|
| 1354 |
+
raise RuntimeError("Filtered SQLite retrieval resolved no selector values.")
|
| 1355 |
+
selector_values = normalized_sequences
|
| 1356 |
+
selector_column = "r.sequence"
|
| 1357 |
+
fetched: list[tuple[Any, ...]] = []
|
| 1358 |
+
unique_values = tuple(dict.fromkeys(selector_values))
|
| 1359 |
+
for start in range(0, len(unique_values), 900):
|
| 1360 |
+
chunk = unique_values[start : start + 900]
|
| 1361 |
+
placeholders = ",".join("?" for _ in chunk)
|
| 1362 |
+
fetched.extend(
|
| 1363 |
+
connection.execute(
|
| 1364 |
+
f"{row_prefix} AND {selector_column} IN ({placeholders}) "
|
| 1365 |
+
"ORDER BY r.position",
|
| 1366 |
+
(selected_run, *chunk),
|
| 1367 |
+
).fetchall()
|
| 1368 |
+
)
|
| 1369 |
+
value_index = (
|
| 1370 |
+
0 if normalized_positions is not None else (1 if normalized_ids is not None else 2)
|
| 1371 |
+
)
|
| 1372 |
+
matched: dict[Any, list[tuple[Any, ...]]] = {}
|
| 1373 |
+
for fetched_row in sorted(fetched, key=lambda item: int(item[0])):
|
| 1374 |
+
matched.setdefault(fetched_row[value_index], []).append(fetched_row)
|
| 1375 |
+
missing = [value for value in selector_values if value not in matched]
|
| 1376 |
+
if missing:
|
| 1377 |
+
raise KeyError(f"SQLite embedding selectors were not found: {missing!r}.")
|
| 1378 |
+
rows = [
|
| 1379 |
+
fetched_row for value in selector_values for fetched_row in matched.get(value, ())
|
| 1380 |
+
]
|
| 1381 |
+
|
| 1382 |
+
if rows is None:
|
| 1383 |
+
return EmbeddingResult(
|
| 1384 |
+
_SQLiteRecordSequence(path, selected_run, int(record_count)),
|
| 1385 |
+
metadata,
|
| 1386 |
+
)
|
| 1387 |
+
records = [_sqlite_record_from_row(path, selected_run, selected_row) for selected_row in rows]
|
| 1388 |
+
if supplied_selectors:
|
| 1389 |
+
metadata = dict(metadata)
|
| 1390 |
+
metadata["selection"] = {
|
| 1391 |
+
"kind": (
|
| 1392 |
+
"positions"
|
| 1393 |
+
if normalized_positions is not None
|
| 1394 |
+
else "record_ids"
|
| 1395 |
+
if normalized_ids is not None
|
| 1396 |
+
else "sequences"
|
| 1397 |
+
),
|
| 1398 |
+
"count": len(rows),
|
| 1399 |
+
"duplicate_policy": "preserve-request-order",
|
| 1400 |
+
}
|
| 1401 |
+
return EmbeddingResult(records, metadata)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
def load_legacy_pth(path: str | Path, *, allow_unsafe_pickle: bool = False) -> EmbeddingResult:
|
| 1405 |
+
"""Import a legacy mapping-only ``.pth`` file after explicit opt-in."""
|
| 1406 |
+
|
| 1407 |
+
if not allow_unsafe_pickle:
|
| 1408 |
+
raise ValueError(
|
| 1409 |
+
"Legacy .pth loading can execute pickle payloads. Pass "
|
| 1410 |
+
"allow_unsafe_pickle=True only for a trusted file."
|
| 1411 |
+
)
|
| 1412 |
+
payload = torch.load(Path(path), map_location="cpu", weights_only=False)
|
| 1413 |
+
if not isinstance(payload, dict):
|
| 1414 |
+
raise ValueError("A legacy .pth embedding file must contain a mapping.")
|
| 1415 |
+
records: list[EmbeddingRecord] = []
|
| 1416 |
+
for position, (sequence, X) in enumerate(payload.items()):
|
| 1417 |
+
if not isinstance(sequence, str) or not isinstance(X, Tensor):
|
| 1418 |
+
raise ValueError("Legacy embedding mappings must use str keys and Tensor values.")
|
| 1419 |
+
records.append(EmbeddingRecord(str(position), sequence, X.detach().cpu()))
|
| 1420 |
+
return EmbeddingResult(records, {"format": "legacy-pth", "unsafe_pickle": True})
|
| 1421 |
+
|
| 1422 |
+
|
| 1423 |
+
_LEGACY_COMPACT_VERSION = 0x01
|
| 1424 |
+
_LEGACY_CODE_DTYPES: dict[int, tuple[np.dtype[Any], torch.dtype]] = {
|
| 1425 |
+
0: (np.dtype(np.float16), torch.float16),
|
| 1426 |
+
# Legacy BF16 blobs stored FP16 payload bytes and converted back to BF16.
|
| 1427 |
+
1: (np.dtype(np.float16), torch.bfloat16),
|
| 1428 |
+
2: (np.dtype(np.float32), torch.float32),
|
| 1429 |
+
}
|
| 1430 |
+
|
| 1431 |
+
|
| 1432 |
+
def _decode_legacy_sqlite_blob(
|
| 1433 |
+
data: bytes,
|
| 1434 |
+
*,
|
| 1435 |
+
fallback_shape: tuple[int, ...] | None,
|
| 1436 |
+
allow_unsafe_pickle: bool,
|
| 1437 |
+
) -> Tensor:
|
| 1438 |
+
if len(data) >= 6 and data[0] == _LEGACY_COMPACT_VERSION:
|
| 1439 |
+
dtype_code = int(data[1])
|
| 1440 |
+
if dtype_code not in _LEGACY_CODE_DTYPES:
|
| 1441 |
+
raise ValueError(f"Unsupported legacy compact dtype code {dtype_code}.")
|
| 1442 |
+
(ndim,) = struct.unpack_from("<i", data, 2)
|
| 1443 |
+
if ndim < 0 or ndim > 16 or len(data) < 6 + 4 * ndim:
|
| 1444 |
+
raise ValueError("Malformed legacy compact embedding header.")
|
| 1445 |
+
shape = tuple(int(value) for value in struct.unpack_from(f"<{ndim}i", data, 6))
|
| 1446 |
+
if any(size < 0 for size in shape):
|
| 1447 |
+
raise ValueError("Malformed negative legacy embedding dimension.")
|
| 1448 |
+
numpy_dtype, target_dtype = _LEGACY_CODE_DTYPES[dtype_code]
|
| 1449 |
+
offset = 6 + 4 * ndim
|
| 1450 |
+
expected = int(np.prod(shape, dtype=np.int64)) * numpy_dtype.itemsize
|
| 1451 |
+
if len(data) - offset != expected:
|
| 1452 |
+
raise ValueError("Legacy compact embedding payload length does not match shape.")
|
| 1453 |
+
array = np.frombuffer(data, dtype=numpy_dtype, offset=offset).copy().reshape(shape)
|
| 1454 |
+
return torch.from_numpy(array).to(dtype=target_dtype)
|
| 1455 |
+
|
| 1456 |
+
try:
|
| 1457 |
+
loaded = torch.load(io.BytesIO(data), map_location="cpu", weights_only=True)
|
| 1458 |
+
except Exception as safe_error:
|
| 1459 |
+
if allow_unsafe_pickle:
|
| 1460 |
+
loaded = torch.load(io.BytesIO(data), map_location="cpu", weights_only=False)
|
| 1461 |
+
elif fallback_shape is None:
|
| 1462 |
+
raise ValueError(
|
| 1463 |
+
"Legacy embedding blob is neither compact nor safely loadable. "
|
| 1464 |
+
"Provide fallback_shape for raw FP32 bytes, or set "
|
| 1465 |
+
"allow_unsafe_pickle=True only for a trusted database."
|
| 1466 |
+
) from safe_error
|
| 1467 |
+
else:
|
| 1468 |
+
expected = int(np.prod(fallback_shape, dtype=np.int64)) * 4
|
| 1469 |
+
if len(data) != expected:
|
| 1470 |
+
raise ValueError(
|
| 1471 |
+
"Legacy raw FP32 payload length does not match fallback_shape."
|
| 1472 |
+
) from safe_error
|
| 1473 |
+
array = np.frombuffer(data, dtype=np.float32).copy().reshape(fallback_shape)
|
| 1474 |
+
return torch.from_numpy(array)
|
| 1475 |
+
if not isinstance(loaded, Tensor):
|
| 1476 |
+
raise ValueError("Legacy serialized embedding payload must contain one tensor.")
|
| 1477 |
+
return loaded.detach().cpu()
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
def convert_legacy_sqlite(
|
| 1481 |
+
source: str | Path,
|
| 1482 |
+
output: str | Path,
|
| 1483 |
+
*,
|
| 1484 |
+
fallback_shape: tuple[int, ...] | None = None,
|
| 1485 |
+
allow_unsafe_pickle: bool = False,
|
| 1486 |
+
metadata: dict[str, Any] | None = None,
|
| 1487 |
+
) -> EmbeddingResult:
|
| 1488 |
+
"""Convert the v0 ``embeddings(sequence, embedding)`` database safely.
|
| 1489 |
+
|
| 1490 |
+
The source is opened read-only. Compact blobs and ``weights_only`` Torch
|
| 1491 |
+
tensors are accepted by default. Unsafe general pickle deserialization
|
| 1492 |
+
remains an explicit opt-in.
|
| 1493 |
+
"""
|
| 1494 |
+
|
| 1495 |
+
source_path = Path(source)
|
| 1496 |
+
output_path = Path(output)
|
| 1497 |
+
if source_path.resolve() == output_path.resolve():
|
| 1498 |
+
raise ValueError("Legacy SQLite conversion requires a different output path.")
|
| 1499 |
+
if fallback_shape is not None and (
|
| 1500 |
+
not fallback_shape or any(not isinstance(size, int) or size < 0 for size in fallback_shape)
|
| 1501 |
+
):
|
| 1502 |
+
raise ValueError("fallback_shape must contain non-negative integer dimensions.")
|
| 1503 |
+
with _connect_sqlite_read_only(source_path) as connection:
|
| 1504 |
+
columns = {
|
| 1505 |
+
str(row[1]) for row in connection.execute("PRAGMA table_info(embeddings)").fetchall()
|
| 1506 |
+
}
|
| 1507 |
+
if not {"sequence", "embedding"}.issubset(columns):
|
| 1508 |
+
raise ValueError("Legacy SQLite database must contain embeddings(sequence, embedding).")
|
| 1509 |
+
rows = connection.execute(
|
| 1510 |
+
"SELECT sequence, embedding FROM embeddings ORDER BY rowid"
|
| 1511 |
+
).fetchall()
|
| 1512 |
+
if not rows:
|
| 1513 |
+
raise ValueError("Legacy SQLite database contains no embeddings.")
|
| 1514 |
+
|
| 1515 |
+
records: list[EmbeddingRecord] = []
|
| 1516 |
+
content_digest = hashlib.sha256()
|
| 1517 |
+
for position, (sequence, data) in enumerate(rows):
|
| 1518 |
+
if not isinstance(sequence, str) or not sequence:
|
| 1519 |
+
raise ValueError("Legacy embedding sequences must be non-empty strings.")
|
| 1520 |
+
if not isinstance(data, bytes):
|
| 1521 |
+
data = bytes(data)
|
| 1522 |
+
tensor = _decode_legacy_sqlite_blob(
|
| 1523 |
+
data,
|
| 1524 |
+
fallback_shape=fallback_shape,
|
| 1525 |
+
allow_unsafe_pickle=allow_unsafe_pickle,
|
| 1526 |
+
)
|
| 1527 |
+
tensor_digest = tensor_sha256(tensor)
|
| 1528 |
+
for value in (sequence.encode("utf-8"), tensor_digest.encode("ascii")):
|
| 1529 |
+
content_digest.update(len(value).to_bytes(8, "big"))
|
| 1530 |
+
content_digest.update(value)
|
| 1531 |
+
records.append(EmbeddingRecord(str(position), sequence, tensor))
|
| 1532 |
+
|
| 1533 |
+
content_sha256 = content_digest.hexdigest()
|
| 1534 |
+
run_fingerprint = hashlib.sha256(
|
| 1535 |
+
f"fastplms-legacy-sqlite-v1:{content_sha256}".encode("ascii")
|
| 1536 |
+
).hexdigest()
|
| 1537 |
+
converted_metadata: dict[str, Any] = {
|
| 1538 |
+
"format_version": 1,
|
| 1539 |
+
"run_fingerprint": run_fingerprint,
|
| 1540 |
+
"source_format": "legacy-fastplms-sqlite-v0",
|
| 1541 |
+
"source_content_sha256": content_sha256,
|
| 1542 |
+
"unsafe_pickle": allow_unsafe_pickle,
|
| 1543 |
+
"complete": True,
|
| 1544 |
+
}
|
| 1545 |
+
if metadata:
|
| 1546 |
+
converted_metadata["conversion_metadata"] = _jsonable(metadata)
|
| 1547 |
+
return save_sqlite_result(
|
| 1548 |
+
EmbeddingResult(records, converted_metadata),
|
| 1549 |
+
output_path,
|
| 1550 |
+
)
|
| 1551 |
+
|
| 1552 |
+
|
| 1553 |
+
def save_result(
|
| 1554 |
+
result: EmbeddingResult,
|
| 1555 |
+
path: str | Path,
|
| 1556 |
+
*,
|
| 1557 |
+
format: str = "safetensors",
|
| 1558 |
+
shard_size: int = DEFAULT_SHARD_SIZE,
|
| 1559 |
+
) -> EmbeddingResult:
|
| 1560 |
+
if format == "safetensors":
|
| 1561 |
+
return save_safetensors_result(result, path, shard_size=shard_size)
|
| 1562 |
+
if format == "sqlite":
|
| 1563 |
+
return save_sqlite_result(result, path)
|
| 1564 |
+
if format == "pth":
|
| 1565 |
+
raise ValueError("Writing pickle-based .pth embeddings is not supported.")
|
| 1566 |
+
raise ValueError("format must be 'safetensors' or 'sqlite'.")
|
| 1567 |
+
|
| 1568 |
+
|
| 1569 |
+
def load_result(path: str | Path, *, format: str = "safetensors") -> EmbeddingResult:
|
| 1570 |
+
if format == "safetensors":
|
| 1571 |
+
return load_safetensors_result(path)
|
| 1572 |
+
if format == "sqlite":
|
| 1573 |
+
return load_sqlite_result(path)
|
| 1574 |
+
raise ValueError("format must be 'safetensors' or 'sqlite'.")
|
| 1575 |
+
|
| 1576 |
+
|
| 1577 |
+
__all__ = [
|
| 1578 |
+
"DEFAULT_SHARD_SIZE",
|
| 1579 |
+
"SafetensorsStreamWriter",
|
| 1580 |
+
"append_sqlite_records",
|
| 1581 |
+
"convert_legacy_sqlite",
|
| 1582 |
+
"garbage_collect_safetensors_generations",
|
| 1583 |
+
"initialize_sqlite_run",
|
| 1584 |
+
"load_legacy_pth",
|
| 1585 |
+
"load_result",
|
| 1586 |
+
"load_safetensors_result",
|
| 1587 |
+
"load_sqlite_result",
|
| 1588 |
+
"safetensors_result_exists",
|
| 1589 |
+
"save_result",
|
| 1590 |
+
"save_safetensors_result",
|
| 1591 |
+
"save_sqlite_result",
|
| 1592 |
+
"tensor_sha256",
|
| 1593 |
+
"update_sqlite_run_metadata",
|
| 1594 |
+
]
|
fastplms/embeddings/types.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public value types for dataset embedding."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from typing import Any, Literal, overload
|
| 8 |
+
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True, slots=True)
|
| 13 |
+
class EmbeddingInput:
|
| 14 |
+
"""One named protein sequence supplied to :func:`embed_dataset`."""
|
| 15 |
+
|
| 16 |
+
id: str
|
| 17 |
+
sequence: str
|
| 18 |
+
|
| 19 |
+
def __post_init__(self) -> None:
|
| 20 |
+
if not isinstance(self.id, str) or not self.id:
|
| 21 |
+
raise ValueError("EmbeddingInput.id must be a non-empty string.")
|
| 22 |
+
if not isinstance(self.sequence, str) or not self.sequence:
|
| 23 |
+
raise ValueError("EmbeddingInput.sequence must be a non-empty string.")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True, slots=True)
|
| 27 |
+
class LazyTensorReference:
|
| 28 |
+
"""A tensor stored outside memory and loaded only when requested."""
|
| 29 |
+
|
| 30 |
+
source: str
|
| 31 |
+
key: str
|
| 32 |
+
dtype: str
|
| 33 |
+
shape: tuple[int, ...]
|
| 34 |
+
sha256: str
|
| 35 |
+
_loader: Callable[[], Tensor] = field(repr=False, compare=False)
|
| 36 |
+
|
| 37 |
+
def load(self, *, verify: bool = True) -> Tensor:
|
| 38 |
+
"""Load X and optionally verify its content digest."""
|
| 39 |
+
|
| 40 |
+
if not isinstance(verify, bool):
|
| 41 |
+
raise TypeError("verify must be a boolean.")
|
| 42 |
+
X = self._loader()
|
| 43 |
+
if not isinstance(X, Tensor):
|
| 44 |
+
raise TypeError(f"Stored tensor loader for {self.key!r} must return a Tensor.")
|
| 45 |
+
if tuple(X.shape) != self.shape:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"Stored tensor {self.key!r} has shape {tuple(X.shape)}, expected {self.shape}."
|
| 48 |
+
)
|
| 49 |
+
dtype = str(X.dtype).removeprefix("torch.")
|
| 50 |
+
if dtype != self.dtype:
|
| 51 |
+
raise ValueError(
|
| 52 |
+
f"Stored tensor {self.key!r} has dtype {dtype!r}, expected {self.dtype!r}."
|
| 53 |
+
)
|
| 54 |
+
if verify:
|
| 55 |
+
from .storage import tensor_sha256
|
| 56 |
+
|
| 57 |
+
digest = tensor_sha256(X)
|
| 58 |
+
if digest != self.sha256:
|
| 59 |
+
raise ValueError(f"Stored tensor {self.key!r} failed SHA-256 verification.")
|
| 60 |
+
return X
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
TensorValue = Tensor | LazyTensorReference
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True, slots=True)
|
| 67 |
+
class EmbeddingRecord:
|
| 68 |
+
"""One ordered embedding result."""
|
| 69 |
+
|
| 70 |
+
id: str
|
| 71 |
+
sequence: str
|
| 72 |
+
tensor: TensorValue
|
| 73 |
+
|
| 74 |
+
def __post_init__(self) -> None:
|
| 75 |
+
if not isinstance(self.id, str) or not self.id:
|
| 76 |
+
raise ValueError("EmbeddingRecord.id must be a non-empty string.")
|
| 77 |
+
if not isinstance(self.sequence, str) or not self.sequence:
|
| 78 |
+
raise ValueError("EmbeddingRecord.sequence must be a non-empty string.")
|
| 79 |
+
if not isinstance(self.tensor, (Tensor, LazyTensorReference)):
|
| 80 |
+
raise TypeError("EmbeddingRecord.tensor must be a Tensor or LazyTensorReference.")
|
| 81 |
+
|
| 82 |
+
def load_tensor(self, *, verify: bool = True) -> Tensor:
|
| 83 |
+
"""Return X regardless of whether this record is memory-backed or lazy."""
|
| 84 |
+
|
| 85 |
+
if not isinstance(verify, bool):
|
| 86 |
+
raise TypeError("verify must be a boolean.")
|
| 87 |
+
if isinstance(self.tensor, LazyTensorReference):
|
| 88 |
+
return self.tensor.load(verify=verify)
|
| 89 |
+
return self.tensor
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class EmbeddingResult(Sequence[EmbeddingRecord]):
|
| 93 |
+
"""Ordered embedding records and the metadata needed to reproduce them."""
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
records: Sequence[EmbeddingRecord],
|
| 98 |
+
metadata: Mapping[str, Any] | None = None,
|
| 99 |
+
) -> None:
|
| 100 |
+
self.records: Sequence[EmbeddingRecord] = (
|
| 101 |
+
records if getattr(records, "_fastplms_immutable_sequence", False) else tuple(records)
|
| 102 |
+
)
|
| 103 |
+
self.metadata = dict(metadata or {})
|
| 104 |
+
|
| 105 |
+
def __len__(self) -> int:
|
| 106 |
+
return len(self.records)
|
| 107 |
+
|
| 108 |
+
def __iter__(self) -> Iterator[EmbeddingRecord]:
|
| 109 |
+
return iter(self.records)
|
| 110 |
+
|
| 111 |
+
@overload
|
| 112 |
+
def __getitem__(self, index: int, /) -> EmbeddingRecord: ...
|
| 113 |
+
|
| 114 |
+
@overload
|
| 115 |
+
def __getitem__(self, index: slice, /) -> Sequence[EmbeddingRecord]: ...
|
| 116 |
+
|
| 117 |
+
def __getitem__(self, index: int | slice) -> EmbeddingRecord | Sequence[EmbeddingRecord]:
|
| 118 |
+
return self.records[index]
|
| 119 |
+
|
| 120 |
+
def as_dict(
|
| 121 |
+
self,
|
| 122 |
+
*,
|
| 123 |
+
key: Literal["id", "sequence"] = "id",
|
| 124 |
+
duplicates: Literal["error", "first", "last"] = "error",
|
| 125 |
+
materialize: bool = True,
|
| 126 |
+
) -> dict[str, TensorValue]:
|
| 127 |
+
"""Convert records to a mapping under an explicit duplicate policy."""
|
| 128 |
+
|
| 129 |
+
if key not in {"id", "sequence"}:
|
| 130 |
+
raise ValueError("key must be 'id' or 'sequence'.")
|
| 131 |
+
if duplicates not in {"error", "first", "last"}:
|
| 132 |
+
raise ValueError("duplicates must be 'error', 'first', or 'last'.")
|
| 133 |
+
if not isinstance(materialize, bool):
|
| 134 |
+
raise TypeError("materialize must be a boolean.")
|
| 135 |
+
output: dict[str, TensorValue] = {}
|
| 136 |
+
for record in self.records:
|
| 137 |
+
record_key = getattr(record, key)
|
| 138 |
+
if record_key in output:
|
| 139 |
+
if duplicates == "error":
|
| 140 |
+
raise ValueError(
|
| 141 |
+
f"Duplicate {key} {record_key!r}; choose duplicates='first' "
|
| 142 |
+
"or duplicates='last' explicitly."
|
| 143 |
+
)
|
| 144 |
+
if duplicates == "first":
|
| 145 |
+
continue
|
| 146 |
+
output[record_key] = record.load_tensor() if materialize else record.tensor
|
| 147 |
+
return output
|
| 148 |
+
|
| 149 |
+
def materialize(self, *, verify: bool = True) -> EmbeddingResult:
|
| 150 |
+
"""Return an equivalent result with every X loaded into CPU memory."""
|
| 151 |
+
|
| 152 |
+
if not isinstance(verify, bool):
|
| 153 |
+
raise TypeError("verify must be a boolean.")
|
| 154 |
+
return EmbeddingResult(
|
| 155 |
+
[
|
| 156 |
+
EmbeddingRecord(
|
| 157 |
+
id=record.id,
|
| 158 |
+
sequence=record.sequence,
|
| 159 |
+
tensor=record.load_tensor(verify=verify),
|
| 160 |
+
)
|
| 161 |
+
for record in self.records
|
| 162 |
+
],
|
| 163 |
+
self.metadata,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclass(frozen=True, slots=True)
|
| 168 |
+
class EmbeddingBatch:
|
| 169 |
+
"""Internal model-to-runner contract.
|
| 170 |
+
|
| 171 |
+
``X`` has shape ``(b, l, d)`` and ``residue_mask`` has shape ``(b, l)``.
|
| 172 |
+
``attentions`` may contain layer/head attention matrices for ``parti``.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
X: Tensor
|
| 176 |
+
residue_mask: Tensor
|
| 177 |
+
attentions: Tensor | tuple[Tensor, ...] | None = None
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
__all__ = [
|
| 181 |
+
"EmbeddingBatch",
|
| 182 |
+
"EmbeddingInput",
|
| 183 |
+
"EmbeddingRecord",
|
| 184 |
+
"EmbeddingResult",
|
| 185 |
+
"LazyTensorReference",
|
| 186 |
+
"TensorValue",
|
| 187 |
+
]
|
fastplms/models.toml
ADDED
|
@@ -0,0 +1,1223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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baa",
|
| 5 |
+
]
|
| 6 |
+
|
| 7 |
+
[[attention_kernels]]
|
| 8 |
+
implementation = "flash_attention_2"
|
| 9 |
+
repository = "kernels-community/flash-attn2"
|
| 10 |
+
revision = "db6b51744f0cd7061386442c09df890fc6d9f47e"
|
| 11 |
+
version = 2
|
| 12 |
+
expected_variant = "flash_attn2"
|
| 13 |
+
dtypes = ["bfloat16"]
|
| 14 |
+
|
| 15 |
+
[[attention_kernels]]
|
| 16 |
+
implementation = "flash_attention_3"
|
| 17 |
+
repository = "kernels-community/flash-attn3"
|
| 18 |
+
revision = "43f0bd269777115d94ff826e0d113ce9c1c9087b"
|
| 19 |
+
version = 1
|
| 20 |
+
expected_variant = "flash_attn3"
|
| 21 |
+
dtypes = ["bfloat16"]
|
| 22 |
+
|
| 23 |
+
[[runtime_assets]]
|
| 24 |
+
id = "esmfold2_ccd"
|
| 25 |
+
repository = "biohub/ESMFold2"
|
| 26 |
+
revision = "1ebf0e3481a5184eb6171d40615c79e384b48796"
|
| 27 |
+
path = "ccd.pkl"
|
| 28 |
+
sha256 = "9ff44b1927c6b9198e38ffe0928706827a09a350c15530beeeabebfa88038fc5"
|
| 29 |
+
size = 417306584
|
| 30 |
+
consumer_family = "esmfold2"
|
| 31 |
+
trust_kind = "hash_pinned_pickle"
|
| 32 |
+
license = "MIT"
|
| 33 |
+
offline_behavior = "requires_cached_verified_file"
|
| 34 |
+
|
| 35 |
+
[[upstreams]]
|
| 36 |
+
id = "ankh"
|
| 37 |
+
path = "vendor/upstream/ankh"
|
| 38 |
+
url = "https://github.com/agemagician/Ankh.git"
|
| 39 |
+
revision = "02b4e25ce5389b9e771c9df6e546c62af1216f8e"
|
| 40 |
+
license = "CC-BY-NC-SA-4.0"
|
| 41 |
+
license_files = ["LICENSE.md"]
|
| 42 |
+
license_digests = ["LICENSE.md=sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088"]
|
| 43 |
+
distribution_files = ["LICENSE.md=sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088"]
|
| 44 |
+
|
| 45 |
+
[[upstreams]]
|
| 46 |
+
id = "biohub-esm"
|
| 47 |
+
path = "vendor/upstream/biohub-esm"
|
| 48 |
+
url = "https://github.com/Biohub/esm.git"
|
| 49 |
+
revision = "82ee35553d39169d678f784c8d3f8712ffd7d2c4"
|
| 50 |
+
license = "MIT"
|
| 51 |
+
license_files = ["LICENSE.md", "THIRD_PARTY_NOTICE.md"]
|
| 52 |
+
license_digests = [
|
| 53 |
+
"LICENSE.md=sha256:b63df9ca1dd96b3b21eec226b51b236d0bd152ac20eafc43aad46bf832b48d8a",
|
| 54 |
+
"THIRD_PARTY_NOTICE.md=sha256:5bff8515ba4e0f53abdc43714c180b79c5b606160497d98de741a369cb9b6a23",
|
| 55 |
+
]
|
| 56 |
+
distribution_files = [
|
| 57 |
+
"LICENSE.md=sha256:b63df9ca1dd96b3b21eec226b51b236d0bd152ac20eafc43aad46bf832b48d8a",
|
| 58 |
+
"THIRD_PARTY_NOTICE.md=sha256:5bff8515ba4e0f53abdc43714c180b79c5b606160497d98de741a369cb9b6a23",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
[[upstreams]]
|
| 62 |
+
id = "biohub-transformers"
|
| 63 |
+
path = "vendor/upstream/biohub-transformers"
|
| 64 |
+
url = "https://github.com/Biohub/transformers.git"
|
| 65 |
+
revision = "3a8956fb4d4ea16b0ec8e71deef2c2909b6a5cbf"
|
| 66 |
+
license = "Apache-2.0"
|
| 67 |
+
license_files = ["LICENSE"]
|
| 68 |
+
license_digests = ["LICENSE=sha256:77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049"]
|
| 69 |
+
distribution_files = ["LICENSE=sha256:77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049"]
|
| 70 |
+
|
| 71 |
+
[[upstreams]]
|
| 72 |
+
id = "boltz"
|
| 73 |
+
path = "vendor/upstream/boltz"
|
| 74 |
+
url = "https://github.com/jwohlwend/boltz.git"
|
| 75 |
+
revision = "b1ebfc46ecf57f5414e0d1a6f9027bbb122c53bc"
|
| 76 |
+
license = "MIT"
|
| 77 |
+
license_files = ["LICENSE"]
|
| 78 |
+
license_digests = ["LICENSE=sha256:f0667fd5e66c51e1ba8ddaa0249c6d7225b30037e02c45782d8f2c2943ac2617"]
|
| 79 |
+
distribution_files = ["LICENSE=sha256:f0667fd5e66c51e1ba8ddaa0249c6d7225b30037e02c45782d8f2c2943ac2617"]
|
| 80 |
+
|
| 81 |
+
[[upstreams]]
|
| 82 |
+
id = "dplm"
|
| 83 |
+
path = "vendor/upstream/dplm"
|
| 84 |
+
url = "https://github.com/bytedance/dplm.git"
|
| 85 |
+
revision = "8a2e15e53416b4536f03f79ad1f6f6a9cbd5e19d"
|
| 86 |
+
license = "Apache-2.0"
|
| 87 |
+
license_files = ["LICENSE"]
|
| 88 |
+
license_digests = ["LICENSE=sha256:cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"]
|
| 89 |
+
distribution_files = [
|
| 90 |
+
"LICENSE=sha256:cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
| 91 |
+
"PROVENANCE.md=sha256:a659f74be9073cf1ad2d2f7071531ca56959b421f111152cf4c41184ace5970e",
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
[[upstreams]]
|
| 95 |
+
id = "e1"
|
| 96 |
+
path = "vendor/upstream/e1"
|
| 97 |
+
url = "https://github.com/Profluent-AI/E1.git"
|
| 98 |
+
revision = "bfd2620a602248499f3d2583d85a7ecddf0b6e02"
|
| 99 |
+
license = "Apache-2.0 AND Profluent-E1-Agreement"
|
| 100 |
+
license_files = ["LICENSE", "ATTRIBUTION", "NOTICE"]
|
| 101 |
+
license_digests = [
|
| 102 |
+
"LICENSE=sha256:8ef1dd556091544db3044164a8015424a3dcb3450fb3765a81b88463551bbe81",
|
| 103 |
+
"ATTRIBUTION=sha256:deb22b250f6491b649eda5c63e080dd56486b8d2736cea6a52ef875436214367",
|
| 104 |
+
"NOTICE=sha256:6de9db0320b4ee82f665c0951d8fd4cd53701a659c9dbce9bc3e3ea6afc4c6b3",
|
| 105 |
+
]
|
| 106 |
+
distribution_files = [
|
| 107 |
+
"LICENSE=sha256:8ef1dd556091544db3044164a8015424a3dcb3450fb3765a81b88463551bbe81",
|
| 108 |
+
"ATTRIBUTION=sha256:deb22b250f6491b649eda5c63e080dd56486b8d2736cea6a52ef875436214367",
|
| 109 |
+
"NOTICE=sha256:6de9db0320b4ee82f665c0951d8fd4cd53701a659c9dbce9bc3e3ea6afc4c6b3",
|
| 110 |
+
"Apache-2.0.txt=sha256:cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
| 111 |
+
"BSD-3-Clause.txt=sha256:36e1987f2f17db7f8ad36cd7a37dbb7aeaaf0ab68b97ab4b9d3556f3a7a76ae8",
|
| 112 |
+
"MODIFICATIONS.md=sha256:2506f47c0f5475af8e8ff2cff13eb8b79e8e25a08a054cdd617bf336536750ca",
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
[[upstreams]]
|
| 116 |
+
id = "fair-esm"
|
| 117 |
+
path = "vendor/upstream/fair-esm"
|
| 118 |
+
url = "https://github.com/facebookresearch/esm.git"
|
| 119 |
+
revision = "2b369911bb5b4b0dda914521b9475cad1656b2ac"
|
| 120 |
+
license = "MIT"
|
| 121 |
+
license_files = ["LICENSE"]
|
| 122 |
+
license_digests = ["LICENSE=sha256:da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93"]
|
| 123 |
+
distribution_files = [
|
| 124 |
+
"LICENSE=sha256:da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93",
|
| 125 |
+
"PROVENANCE.md=sha256:950adb94daf15e646ddf226dacfe2a8e77801aa0793e439a9a3490a48eb666e7",
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
[[upstreams]]
|
| 129 |
+
id = "openfold"
|
| 130 |
+
path = "vendor/upstream/openfold"
|
| 131 |
+
url = "https://github.com/aqlaboratory/openfold.git"
|
| 132 |
+
revision = "4b41059694619831a7db195b7e0988fc4ff3a307"
|
| 133 |
+
license = "Apache-2.0"
|
| 134 |
+
license_files = ["LICENSE"]
|
| 135 |
+
license_digests = ["LICENSE=sha256:cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"]
|
| 136 |
+
distribution_files = [
|
| 137 |
+
"LICENSE=sha256:cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
| 138 |
+
"MODIFICATIONS.md=sha256:fd6f0aa1086a0c996cf967b326d18e965660cda0ad5c7f36a3474a8490720da3",
|
| 139 |
+
"PROVENANCE.md=sha256:48c903db43a217a3126afaefbac60b7ddac7efda2dfcc0cbff0bffc7d6c30081",
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
[[upstreams]]
|
| 143 |
+
id = "protein-ttt"
|
| 144 |
+
path = "vendor/upstream/protein-ttt"
|
| 145 |
+
url = "https://github.com/anton-bushuiev/ProteinTTT.git"
|
| 146 |
+
revision = "fde2817cd84b936167cc76ccabf31e5c0fe49962"
|
| 147 |
+
license = "MIT"
|
| 148 |
+
license_files = ["LICENSE"]
|
| 149 |
+
license_digests = ["LICENSE=sha256:bb01e7d5554f9e2e117172e56551452f68a7818df7bc8e71cd7a776a1d4ba3df"]
|
| 150 |
+
distribution_files = [
|
| 151 |
+
"LICENSE=sha256:bb01e7d5554f9e2e117172e56551452f68a7818df7bc8e71cd7a776a1d4ba3df",
|
| 152 |
+
"PROVENANCE.md=sha256:dc641c37353c2efd50ccbdb316ca4aae495ec02c1563e0e15bac92f75fc482e5",
|
| 153 |
+
]
|
| 154 |
+
|
| 155 |
+
[families.esm2]
|
| 156 |
+
architecture = "ESM2"
|
| 157 |
+
upstreams = ["fair-esm"]
|
| 158 |
+
tokenizer_mode = "tokenizer"
|
| 159 |
+
public_input = "Amino-acid sequences tokenized to residue IDs"
|
| 160 |
+
extra = "core"
|
| 161 |
+
reference_container = "reference-esm2"
|
| 162 |
+
reference_adapter = "tests.parity.support.reference_adapters.esm2"
|
| 163 |
+
attention = ["eager", "sdpa", "flex_attention", "flash_attention_2", "flash_attention_3"]
|
| 164 |
+
dtypes = ["float32", "bfloat16"]
|
| 165 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 166 |
+
precisions = ["default"]
|
| 167 |
+
vram_tier = "sequence"
|
| 168 |
+
checkpoint_license = "MIT"
|
| 169 |
+
hub_license = "mit"
|
| 170 |
+
weights_publication_allowed = true
|
| 171 |
+
state_transform = "esm2_hf_to_fastplms_v1"
|
| 172 |
+
conversion_provenance = "Input: the pinned official ESM2 state dictionary. Transformation: apply the deterministic esm2_hf_to_fastplms_v1 key map while preserving tensor values and materializing the tied input/output embedding values as independent tensors. Output: the pinned Synthyra FastPLMs checkpoint. Validation: release parity compares exact keys and values after the declared non-aliasing transform, tokenizer behavior, and inference. Limitation: any numerical rewrite requires a new transform identifier and exact conversion test."
|
| 173 |
+
representative = "esm2_8m"
|
| 174 |
+
documentation = "docs/models.md#esm2"
|
| 175 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 176 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/_esm_rotary.py", "models/esm2", "models/ttt.py"]
|
| 177 |
+
auto_map = { AutoConfig = "fastplms.models.esm2.modeling_fastesm.FastEsmConfig", AutoModel = "fastplms.models.esm2.modeling_fastesm.FastEsmModel", AutoModelForMaskedLM = "fastplms.models.esm2.modeling_fastesm.FastEsmForMaskedLM", AutoModelForSequenceClassification = "fastplms.models.esm2.modeling_fastesm.FastEsmForSequenceClassification", AutoModelForTokenClassification = "fastplms.models.esm2.modeling_fastesm.FastEsmForTokenClassification" }
|
| 178 |
+
|
| 179 |
+
[families.esm_plusplus]
|
| 180 |
+
architecture = "ESMC"
|
| 181 |
+
upstreams = ["biohub-esm", "biohub-transformers"]
|
| 182 |
+
tokenizer_mode = "tokenizer"
|
| 183 |
+
public_input = "Amino-acid sequences tokenized to residue IDs"
|
| 184 |
+
extra = "core"
|
| 185 |
+
reference_container = "reference-biohub-esm"
|
| 186 |
+
reference_adapter = "tests.parity.support.reference_adapters.esm_plusplus"
|
| 187 |
+
attention = ["eager", "sdpa", "flex_attention", "flash_attention_2", "flash_attention_3"]
|
| 188 |
+
dtypes = ["float32", "bfloat16"]
|
| 189 |
+
bf16_execution = "static_parameters"
|
| 190 |
+
precisions = ["default"]
|
| 191 |
+
vram_tier = "sequence"
|
| 192 |
+
checkpoint_license = "MIT"
|
| 193 |
+
hub_license = "mit"
|
| 194 |
+
weights_publication_allowed = true
|
| 195 |
+
state_transform = "esmc_to_fastplms_v1"
|
| 196 |
+
conversion_provenance = "Input: the pinned Biohub ESMC checkpoint. Transformation: apply the deterministic esmc_to_fastplms_v1 parameter map into the FastPLMs ESMC modules. Output: the pinned Synthyra ESMplusplus checkpoint. Validation: release parity compares keys, shapes, dtypes, values, aliases, and live inference. Limitation: runtime attention and precision selection are not serialized weight transforms."
|
| 197 |
+
representative = "esmc_small"
|
| 198 |
+
documentation = "docs/models.md#esm-and-esmc"
|
| 199 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 200 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/esm_plusplus", "models/ttt.py"]
|
| 201 |
+
auto_map = { AutoConfig = "fastplms.models.esm_plusplus.modeling_esm_plusplus.ESMplusplusConfig", AutoModel = "fastplms.models.esm_plusplus.modeling_esm_plusplus.ESMplusplusModel", AutoModelForMaskedLM = "fastplms.models.esm_plusplus.modeling_esm_plusplus.ESMplusplusForMaskedLM" }
|
| 202 |
+
|
| 203 |
+
[families.esm3]
|
| 204 |
+
architecture = "ESM3"
|
| 205 |
+
upstreams = ["biohub-esm", "biohub-transformers"]
|
| 206 |
+
tokenizer_mode = "tokenizer"
|
| 207 |
+
public_input = "Sequence, structure, and function tracks prepared through the multimodal helpers"
|
| 208 |
+
extra = "core"
|
| 209 |
+
reference_container = "reference-biohub-esm"
|
| 210 |
+
reference_adapter = "tests.parity.support.reference_adapters.esm3"
|
| 211 |
+
attention = ["eager", "sdpa", "flex_attention"]
|
| 212 |
+
dtypes = ["float32", "bfloat16"]
|
| 213 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 214 |
+
precisions = ["default"]
|
| 215 |
+
vram_tier = "large-sequence"
|
| 216 |
+
checkpoint_license = "MIT"
|
| 217 |
+
hub_license = "mit"
|
| 218 |
+
weights_publication_allowed = true
|
| 219 |
+
state_transform = "esm3_to_fastplms_v1"
|
| 220 |
+
conversion_provenance = "Input: the pinned Biohub ESM3 checkpoint. Transformation: apply the deterministic esm3_to_fastplms_v1 parameter map for the supported sequence and multimodal modules and expand BF16 checkpoint tensors to FP32 storage. Output: the pinned Synthyra ESM3 checkpoint. Validation: release parity compares exact state identity after the declared map and live feature behavior. Limitation: unsupported upstream modalities may not be inferred from this record."
|
| 221 |
+
representative = "esm3_small"
|
| 222 |
+
documentation = "docs/models.md#esm3"
|
| 223 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 224 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/esm3", "models/ttt.py"]
|
| 225 |
+
auto_map = { AutoConfig = "fastplms.models.esm3.modeling_esm3.FastESM3Config", AutoModel = "fastplms.models.esm3.modeling_esm3.FastESM3Model" }
|
| 226 |
+
|
| 227 |
+
[families.e1]
|
| 228 |
+
architecture = "E1"
|
| 229 |
+
upstreams = ["e1"]
|
| 230 |
+
tokenizer_mode = "sequence"
|
| 231 |
+
public_input = "Raw amino-acid sequences prepared by the native E1 adapter"
|
| 232 |
+
extra = "core"
|
| 233 |
+
reference_container = "reference-e1"
|
| 234 |
+
reference_adapter = "tests.parity.support.reference_adapters.e1"
|
| 235 |
+
attention = ["sdpa", "flex_attention"]
|
| 236 |
+
dtypes = ["float32", "bfloat16"]
|
| 237 |
+
bf16_execution = "static_parameters"
|
| 238 |
+
precisions = ["default"]
|
| 239 |
+
vram_tier = "sequence"
|
| 240 |
+
checkpoint_license = "Profluent-E1-Agreement"
|
| 241 |
+
hub_license = "other"
|
| 242 |
+
hub_license_name = "Profluent-E1 Clickthrough License Agreement"
|
| 243 |
+
hub_license_link = "https://github.com/Profluent-AI/E1/blob/bfd2620a602248499f3d2583d85a7ecddf0b6e02/LICENSE"
|
| 244 |
+
weights_publication_allowed = true
|
| 245 |
+
state_transform = "e1_to_fastplms_v1"
|
| 246 |
+
conversion_provenance = "Input: the pinned Profluent-E1 checkpoint and tokenizer-free sequence contract. Transformation: apply e1_to_fastplms_v1 to the FastPLMs encoder and official task heads, storing floating tensors in BF16. Output: the pinned Synthyra Profluent-E1 checkpoint. Validation: release parity covers state identity after the declared cast, sequence and RAG preparation, aliases, and inference. Limitation: the FastPLMs scoring extension is not represented as an official E1 head."
|
| 247 |
+
representative = "e1_150m"
|
| 248 |
+
documentation = "docs/models.md#e1"
|
| 249 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 250 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/e1", "models/ttt.py"]
|
| 251 |
+
auto_map = { AutoConfig = "fastplms.models.e1.modeling_e1.E1Config", AutoModel = "fastplms.models.e1.modeling_e1.E1Model", AutoModelForMaskedLM = "fastplms.models.e1.modeling_e1.E1ForMaskedLM", AutoModelForSequenceClassification = "fastplms.models.e1.modeling_e1.E1ForSequenceClassification", AutoModelForTokenClassification = "fastplms.models.e1.modeling_e1.E1ForTokenClassification" }
|
| 252 |
+
|
| 253 |
+
[families.dplm]
|
| 254 |
+
architecture = "DPLM"
|
| 255 |
+
upstreams = ["dplm"]
|
| 256 |
+
tokenizer_mode = "tokenizer"
|
| 257 |
+
public_input = "Amino-acid sequences tokenized to masked or partially masked residue IDs"
|
| 258 |
+
extra = "core"
|
| 259 |
+
reference_container = "reference-dplm"
|
| 260 |
+
reference_adapter = "tests.parity.support.reference_adapters.dplm"
|
| 261 |
+
attention = ["eager", "sdpa", "flex_attention", "flash_attention_3"]
|
| 262 |
+
dtypes = ["float32", "bfloat16"]
|
| 263 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 264 |
+
precisions = ["default"]
|
| 265 |
+
vram_tier = "sequence"
|
| 266 |
+
checkpoint_license = "Apache-2.0"
|
| 267 |
+
hub_license = "apache-2.0"
|
| 268 |
+
weights_publication_allowed = true
|
| 269 |
+
state_transform = "dplm_to_fastplms_v1"
|
| 270 |
+
conversion_provenance = "Input: the pinned official DPLM1 checkpoint. Transformation: apply dplm_to_fastplms_v1, omitting the unused absolute-position table for rotary checkpoints and materializing the tied input/output embedding values as independent tensors. Output: the pinned Synthyra DPLM checkpoint. Validation: release parity compares exact state identity after the declared transform, tokenizer behavior, generation, and inference. License basis: the pinned ByteDance DPLM Apache-2.0 LICENSE and README explicitly scope the repository release to the pretrained DPLM1 and DPLM2 weights; immutable evidence is recorded in LICENSES/dplm/PROVENANCE.md. Limitation: redistribution remains subject to Apache-2.0 and the pinned provenance record; no broader rights are inferred."
|
| 271 |
+
representative = "dplm_150m"
|
| 272 |
+
documentation = "docs/models.md#dplm"
|
| 273 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 274 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/_diffusion_generation.py", "models/_esm_rotary.py", "models/dplm", "models/ttt.py"]
|
| 275 |
+
auto_map = { AutoConfig = "fastplms.models.dplm.modeling_dplm.DPLMConfig", AutoModel = "fastplms.models.dplm.modeling_dplm.DPLMModel", AutoModelForMaskedLM = "fastplms.models.dplm.modeling_dplm.DPLMForMaskedLM", AutoModelForSequenceClassification = "fastplms.models.dplm.modeling_dplm.DPLMForSequenceClassification", AutoModelForTokenClassification = "fastplms.models.dplm.modeling_dplm.DPLMForTokenClassification" }
|
| 276 |
+
|
| 277 |
+
[families.dplm2]
|
| 278 |
+
architecture = "DPLM2"
|
| 279 |
+
upstreams = ["dplm"]
|
| 280 |
+
tokenizer_mode = "tokenizer"
|
| 281 |
+
public_input = "Tokenized amino-acid and structure tracks with explicit modality boundaries"
|
| 282 |
+
extra = "core"
|
| 283 |
+
reference_container = "reference-dplm"
|
| 284 |
+
reference_adapter = "tests.parity.support.reference_adapters.dplm2"
|
| 285 |
+
attention = ["sdpa"]
|
| 286 |
+
dtypes = ["float32", "bfloat16"]
|
| 287 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 288 |
+
precisions = ["default"]
|
| 289 |
+
vram_tier = "sequence"
|
| 290 |
+
checkpoint_license = "Apache-2.0"
|
| 291 |
+
hub_license = "apache-2.0"
|
| 292 |
+
weights_publication_allowed = true
|
| 293 |
+
state_transform = "dplm2_to_fastplms_v1"
|
| 294 |
+
conversion_provenance = "Input: the pinned official DPLM2 checkpoint. Transformation: apply dplm2_to_fastplms_v1, retaining the independent language-model head and trained encoder contact head while omitting the unused absolute-position table for rotary checkpoints. Output: the pinned Synthyra DPLM2 checkpoint. Validation: release parity compares exact keys and values after the declared omission, non-aliasing, tokenizer behavior, generation, and inference. License basis: the pinned ByteDance DPLM Apache-2.0 LICENSE and README explicitly scope the repository release to the pretrained DPLM1 and DPLM2 weights; immutable evidence is recorded in LICENSES/dplm/PROVENANCE.md. Limitation: no head exception is permitted by this record, and redistribution remains subject to Apache-2.0."
|
| 295 |
+
representative = "dplm2_150m"
|
| 296 |
+
documentation = "docs/models.md#dplm2"
|
| 297 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 298 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/_diffusion_generation.py", "models/_esm_rotary.py", "models/dplm2", "models/ttt.py"]
|
| 299 |
+
auto_map = { AutoConfig = "fastplms.models.dplm2.modeling_dplm2.DPLM2Config", AutoModel = "fastplms.models.dplm2.modeling_dplm2.DPLM2Model", AutoModelForMaskedLM = "fastplms.models.dplm2.modeling_dplm2.DPLM2ForMaskedLM", AutoModelForSequenceClassification = "fastplms.models.dplm2.modeling_dplm2.DPLM2ForSequenceClassification", AutoModelForTokenClassification = "fastplms.models.dplm2.modeling_dplm2.DPLM2ForTokenClassification" }
|
| 300 |
+
tokenizer_class = "fastplms.models.dplm2.tokenization_dplm2.DPLM2Tokenizer"
|
| 301 |
+
|
| 302 |
+
[families.ankh]
|
| 303 |
+
architecture = "ANKH"
|
| 304 |
+
upstreams = ["ankh"]
|
| 305 |
+
tokenizer_mode = "tokenizer"
|
| 306 |
+
public_input = "Amino-acid sequences tokenized for encoder or sequence-to-sequence use"
|
| 307 |
+
extra = "core"
|
| 308 |
+
reference_container = "reference-ankh"
|
| 309 |
+
reference_adapter = "tests.parity.support.reference_adapters.ankh"
|
| 310 |
+
attention = ["eager", "sdpa"]
|
| 311 |
+
dtypes = ["float32", "bfloat16"]
|
| 312 |
+
bf16_execution = "static_parameters"
|
| 313 |
+
precisions = ["default"]
|
| 314 |
+
vram_tier = "large-sequence"
|
| 315 |
+
checkpoint_license = "CC-BY-NC-SA-4.0"
|
| 316 |
+
hub_license = "cc-by-nc-sa-4.0"
|
| 317 |
+
weights_publication_allowed = true
|
| 318 |
+
state_transform = "ankh_t5_to_fastplms_v1"
|
| 319 |
+
conversion_provenance = "Input: the pinned official ANKH T5 checkpoint. Transformation: apply ankh_t5_to_fastplms_v1 to the official encoder and sequence-to-sequence heads. Output: the pinned Synthyra ANKH checkpoint. Validation: release parity compares exact mapped state, tokenizer behavior, official heads, and inference. Limitation: the separately named FastPLMs masked-language-model extension is not an official ANKH head."
|
| 320 |
+
representative = "ankh_base"
|
| 321 |
+
documentation = "docs/models.md#ankh"
|
| 322 |
+
test_tiers = ["check", "compliance", "feature", "artifact", "benchmark"]
|
| 323 |
+
requires_complete_weight_publication = true
|
| 324 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/ankh", "models/ttt.py"]
|
| 325 |
+
auto_map = { AutoConfig = "fastplms.models.ankh.modeling_ankh.FastAnkhConfig", AutoModel = "fastplms.models.ankh.modeling_ankh.FastAnkhModel", AutoModelForMaskedLM = "fastplms.models.ankh.modeling_ankh.FastAnkhForMaskedLMExtension", AutoModelForSeq2SeqLM = "fastplms.models.ankh.modeling_ankh.FastAnkhForConditionalGeneration", AutoModelForSequenceClassification = "fastplms.models.ankh.modeling_ankh.FastAnkhForSequenceClassification", AutoModelForTokenClassification = "fastplms.models.ankh.modeling_ankh.FastAnkhForTokenClassification" }
|
| 326 |
+
|
| 327 |
+
[families.boltz2]
|
| 328 |
+
architecture = "Boltz2"
|
| 329 |
+
upstreams = ["boltz"]
|
| 330 |
+
tokenizer_mode = "structure"
|
| 331 |
+
public_input = "Raw amino-acid sequences through the convenience API, or prepared model features"
|
| 332 |
+
extra = "structure"
|
| 333 |
+
reference_container = "reference-boltz2"
|
| 334 |
+
reference_adapter = "tests.parity.support.reference_adapters.boltz"
|
| 335 |
+
attention = ["eager"]
|
| 336 |
+
dtypes = ["float32", "bfloat16"]
|
| 337 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 338 |
+
precisions = ["default"]
|
| 339 |
+
vram_tier = "structure"
|
| 340 |
+
checkpoint_license = "MIT"
|
| 341 |
+
hub_license = "mit"
|
| 342 |
+
weights_publication_allowed = true
|
| 343 |
+
state_transform = "boltz2_inference_core_v1"
|
| 344 |
+
conversion_provenance = "Input: the pinned official Boltz2 checkpoint. Transformation: select and map the supported Boltz2 inference-core parameters with boltz2_inference_core_v1. Output: the pinned Synthyra Boltz2 checkpoint. Validation: release parity covers state identity for the declared subset, feature preparation, seeded inference, and structure outputs. Limitation: this record does not claim support for undeclared upstream training components."
|
| 345 |
+
representative = "boltz2"
|
| 346 |
+
documentation = "docs/models.md#boltz2"
|
| 347 |
+
test_tiers = ["structure", "artifact", "benchmark"]
|
| 348 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "models/boltz"]
|
| 349 |
+
auto_map = { AutoConfig = "fastplms.models.boltz.modeling_boltz2.Boltz2Config", AutoModel = "fastplms.models.boltz.modeling_boltz2.Boltz2Model" }
|
| 350 |
+
|
| 351 |
+
[families.esmfold]
|
| 352 |
+
architecture = "ESMFold"
|
| 353 |
+
upstreams = ["fair-esm", "openfold"]
|
| 354 |
+
tokenizer_mode = "structure"
|
| 355 |
+
public_input = "Raw amino-acid sequences through folding helpers, or prepared residue tensors"
|
| 356 |
+
extra = "structure"
|
| 357 |
+
reference_container = "reference-esmfold"
|
| 358 |
+
reference_adapter = "tests.parity.support.reference_adapters.esmfold"
|
| 359 |
+
attention = ["eager", "sdpa", "flex_attention"]
|
| 360 |
+
dtypes = ["float32", "bfloat16"]
|
| 361 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 362 |
+
precisions = ["default"]
|
| 363 |
+
vram_tier = "structure"
|
| 364 |
+
checkpoint_license = "MIT"
|
| 365 |
+
hub_license = "mit"
|
| 366 |
+
weights_publication_allowed = true
|
| 367 |
+
state_transform = "esmfold_meta_to_fastplms_v1"
|
| 368 |
+
conversion_provenance = "Input: the pinned native Meta ESMFold checkpoint plus its pinned ESM2 backbone. Transformation: apply esmfold_meta_to_fastplms_v1 to map native ESM2 names into the structure-only FastPLMs backbone, retain folding tensors, omit five deterministically reconstructed geometry buffers, omit the folding-unused ESM2 masked-LM and contact-regression heads, and remove the obsolete random FastPLMs TTT head from earlier mirrors. Output: canonical FP32 FastPLMs ESMFold state with an explicit CUDA BF16-autocast execution path. Validation: release parity compares exact mapped keys, shapes, dtypes, values, aliases, semantic configuration, FP32 and BF16-compute seeded inference, and structure metrics with pLDDT normalized to (0, 1). Limitation: ESMFold TTT is rejected because the official checkpoint contains no trained masked-language-model head."
|
| 369 |
+
representative = "esmfold"
|
| 370 |
+
documentation = "docs/models.md#esmfold"
|
| 371 |
+
test_tiers = ["check", "compliance", "structure", "feature", "artifact", "benchmark"]
|
| 372 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/_esm_rotary.py", "models/esmfold"]
|
| 373 |
+
auto_map = { AutoConfig = "fastplms.models.esmfold.modeling_fast_esmfold.FastEsmFoldConfig", AutoModel = "fastplms.models.esmfold.modeling_fast_esmfold.FastEsmForProteinFolding" }
|
| 374 |
+
|
| 375 |
+
[families.esmfold2]
|
| 376 |
+
architecture = "ESMFold2"
|
| 377 |
+
upstreams = ["biohub-esm", "biohub-transformers", "protein-ttt"]
|
| 378 |
+
backbone_model = "esmc_6b"
|
| 379 |
+
tokenizer_mode = "structure"
|
| 380 |
+
public_input = "Raw amino-acid sequences or typed molecular-complex specifications; low-level forward accepts prepared feature tensors"
|
| 381 |
+
extra = "structure"
|
| 382 |
+
reference_container = "reference-esmfold2"
|
| 383 |
+
reference_adapter = "tests.parity.support.reference_adapters.esmfold2"
|
| 384 |
+
attention = ["eager", "sdpa", "flex_attention"]
|
| 385 |
+
dtypes = ["float32", "bfloat16"]
|
| 386 |
+
bf16_execution = "fp32_parameters_autocast"
|
| 387 |
+
precisions = ["auto", "fp32", "bf16", "fp8"]
|
| 388 |
+
experimental_precisions = ["fp8"]
|
| 389 |
+
vram_tier = "structure-6b"
|
| 390 |
+
checkpoint_license = "MIT"
|
| 391 |
+
hub_license = "mit"
|
| 392 |
+
weights_publication_allowed = true
|
| 393 |
+
state_transform = "identity"
|
| 394 |
+
conversion_provenance = "Input: each pinned Biohub ESMFold2 checkpoint and its separately pinned ESMC checkpoint. Transformation: apply identity to preserve the folding checkpoint exactly, load its parameters in FP32 for CUDA BF16-autocast execution, retain canonical BF16 ESMC weights, and optionally rebuild exactly 80 ESMC attention output projections as transient Transformer Engine linears. Output: the corresponding pinned Synthyra ESMFold2 checkpoint plus its declared ESMC precision policy. Validation: release parity covers exact canonical state, learned projection, prepared features, and seeded BF16 folding; experimental FP8 validation covers strict unavailable-device behavior, all four variants, and three BF16-to-FP8 reload cycles on the standard variant. Limitation: only the four manifest-listed ESMFold2 variants are supported; FP8 is experimental, applies only to inference-time ESMC execution, and requires direct CUDA loading with Transformer Engine availability."
|
| 395 |
+
representative = "esmfold2"
|
| 396 |
+
documentation = "docs/esmfold2.md"
|
| 397 |
+
test_tiers = ["check", "compliance", "structure", "feature", "artifact", "benchmark"]
|
| 398 |
+
runtime_paths = ["__init__.py", "registry.py", "runtime.py", "models.toml", "models/__init__.py", "attention", "embeddings", "models/esmfold2", "models/esm_plusplus", "models/ttt.py"]
|
| 399 |
+
auto_map = { AutoConfig = "fastplms.models.esmfold2.configuration_esmfold2.ESMFold2Config", AutoModel = "fastplms.models.esmfold2.modeling_esmfold2.ESMFold2Model" }
|
| 400 |
+
|
| 401 |
+
[[models]]
|
| 402 |
+
id = "esm2_8m"
|
| 403 |
+
family = "esm2"
|
| 404 |
+
size_category = "small"
|
| 405 |
+
generation_contract = "not_applicable"
|
| 406 |
+
official_golden = { metadata = "tests/goldens/esm2_8m.json=sha256:6975e86d1d8f27488bf2a676551feaa48cc19254c9d24b6acb09198122745609", tensors = "tests/goldens/esm2_8m.safetensors=sha256:b40217566c33c71988d28869de353be54a3b3ebfc21fdfd29056e88cf7e99f4c" }
|
| 407 |
+
fast_repo = "Synthyra/ESM2-8M"
|
| 408 |
+
fast_revision = "185ecbd45665d050a8dae326d91886d330c5f9d0"
|
| 409 |
+
fast_files = [
|
| 410 |
+
"config.json=git-sha1:46d0a7b517f59123c6ebc6d1011585731cbab259",
|
| 411 |
+
"model.safetensors=sha256:c824e6ded5fb71c72bc5ac05300699947819023cb26cdaf6897665e6b2645e1b",
|
| 412 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 413 |
+
"tokenizer_config.json=git-sha1:3cfc5db0c6790859a3bc2a4dc053a813acd65295",
|
| 414 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 415 |
+
]
|
| 416 |
+
official_repo = "facebook/esm2_t6_8M_UR50D"
|
| 417 |
+
official_revision = "c731040fcd8d73dceaa04b0a8e6329b345b0f5df"
|
| 418 |
+
official_files = [
|
| 419 |
+
"config.json=git-sha1:c2c6e65a87d9d20d47699ae236d605b80c741dd3",
|
| 420 |
+
"model.safetensors=sha256:24c5fa474c48f3b754b86efe752d5f189d2bcd88190fa2270fc92b2ef3034189",
|
| 421 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 422 |
+
"tokenizer_config.json=git-sha1:3f0d47e841e1cb75257aeaf76d156802899a217e",
|
| 423 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 424 |
+
]
|
| 425 |
+
|
| 426 |
+
[[models.oracle_assets]]
|
| 427 |
+
role = "weights"
|
| 428 |
+
path = "models/esm2_t6_8M_UR50D.pt"
|
| 429 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t6_8M_UR50D.pt"
|
| 430 |
+
sha256 = "46f002a9870c9bdecd0ea887acb1f9a38a6b561e8f8bf8a6990b679b9d31b928"
|
| 431 |
+
size = 30099493
|
| 432 |
+
|
| 433 |
+
[[models.oracle_assets]]
|
| 434 |
+
role = "contact_regression"
|
| 435 |
+
path = "regression/esm2_t6_8M_UR50D-contact-regression.pt"
|
| 436 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/regression/esm2_t6_8M_UR50D-contact-regression.pt"
|
| 437 |
+
sha256 = "8f7a4557d57713b97ba0e484303007efb7230d25299c0ac47a0a1b12a87bbb9d"
|
| 438 |
+
size = 1511
|
| 439 |
+
|
| 440 |
+
[[models]]
|
| 441 |
+
id = "esm2_35m"
|
| 442 |
+
family = "esm2"
|
| 443 |
+
size_category = "small"
|
| 444 |
+
generation_contract = "not_applicable"
|
| 445 |
+
official_golden = { metadata = "tests/goldens/esm2_35m.json=sha256:e919d3ce6d20b6a942d27d92323814ae7594a0129dc9c4de27c5053e96675bcd", tensors = "tests/goldens/esm2_35m.safetensors=sha256:c9b8bb616cf884fb7744521a2fcc6eed23586342d11241e6c9ef16454ec31e17" }
|
| 446 |
+
fast_repo = "Synthyra/ESM2-35M"
|
| 447 |
+
fast_revision = "37ab9f56b41e365b3bd9e25d6fefe9150fd910f0"
|
| 448 |
+
fast_files = [
|
| 449 |
+
"config.json=git-sha1:4d428c9934572f39e2a00db162249971f37c88e4",
|
| 450 |
+
"model.safetensors=sha256:21d95ab6bb9aa91bfec87eff11da61a657b732f2df279cbddbae6a7f1f0bba9c",
|
| 451 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 452 |
+
"tokenizer_config.json=git-sha1:3cfc5db0c6790859a3bc2a4dc053a813acd65295",
|
| 453 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 454 |
+
]
|
| 455 |
+
official_repo = "facebook/esm2_t12_35M_UR50D"
|
| 456 |
+
official_revision = "6fbf070e65b0b7291e7bbcd451118c216cff79d8"
|
| 457 |
+
official_files = [
|
| 458 |
+
"config.json=git-sha1:3f64131bb610ed1ce482c4b5421fc358c785278f",
|
| 459 |
+
"model.safetensors=sha256:e35647818e0e064351d4531ed480d225a002567b4b2b93ad3a9246d753150fc0",
|
| 460 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 461 |
+
"tokenizer_config.json=git-sha1:3f0d47e841e1cb75257aeaf76d156802899a217e",
|
| 462 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 463 |
+
]
|
| 464 |
+
|
| 465 |
+
[[models.oracle_assets]]
|
| 466 |
+
role = "weights"
|
| 467 |
+
path = "models/esm2_t12_35M_UR50D.pt"
|
| 468 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t12_35M_UR50D.pt"
|
| 469 |
+
sha256 = "7f21e80e61d16a71735163ef555d3009afb0c98da74c48e29df08606973cc55e"
|
| 470 |
+
size = 134095705
|
| 471 |
+
|
| 472 |
+
[[models.oracle_assets]]
|
| 473 |
+
role = "contact_regression"
|
| 474 |
+
path = "regression/esm2_t12_35M_UR50D-contact-regression.pt"
|
| 475 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/regression/esm2_t12_35M_UR50D-contact-regression.pt"
|
| 476 |
+
sha256 = "16641e05d830d0ce863dd152dbb8c2f3ddfa3c3ec2a66080152c8abad01d8585"
|
| 477 |
+
size = 1959
|
| 478 |
+
|
| 479 |
+
[[models]]
|
| 480 |
+
id = "esm2_150m"
|
| 481 |
+
family = "esm2"
|
| 482 |
+
size_category = "medium"
|
| 483 |
+
generation_contract = "not_applicable"
|
| 484 |
+
official_golden = { metadata = "tests/goldens/esm2_150m.json=sha256:c04c93486024ba0fa1c81fbfbe92ee79d1d4c7f1cfcc2c9886728522f752feab", tensors = "tests/goldens/esm2_150m.safetensors=sha256:c03fe9916dba137b452a6bbe944c7dc414db4019a6f0921e87b92d4bb6a8a42f" }
|
| 485 |
+
fast_repo = "Synthyra/ESM2-150M"
|
| 486 |
+
fast_revision = "979e0880dfc9e0c0080839b83d9d2dc05b92786a"
|
| 487 |
+
fast_files = [
|
| 488 |
+
"config.json=git-sha1:efeae2af182b7d34dc35740a45f157661e7acdf4",
|
| 489 |
+
"model.safetensors=sha256:d1f7c60f98c31af328381519a750972b6a31b13b97aa7cca2e71b5ae1b3f8f53",
|
| 490 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 491 |
+
"tokenizer_config.json=git-sha1:3cfc5db0c6790859a3bc2a4dc053a813acd65295",
|
| 492 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 493 |
+
]
|
| 494 |
+
official_repo = "facebook/esm2_t30_150M_UR50D"
|
| 495 |
+
official_revision = "a695f6045e2e32885fa60af20c13cb35398ce30c"
|
| 496 |
+
official_files = [
|
| 497 |
+
"config.json=git-sha1:52e04179e6fbad6663a94ea5cc44f09d764c5cd4",
|
| 498 |
+
"model.safetensors=sha256:c3f1da8aea53bddd32c246c86168c23b9fd72341fb9db9a94436f855f5053566",
|
| 499 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 500 |
+
"tokenizer_config.json=git-sha1:3f0d47e841e1cb75257aeaf76d156802899a217e",
|
| 501 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 502 |
+
]
|
| 503 |
+
|
| 504 |
+
[[models.oracle_assets]]
|
| 505 |
+
role = "weights"
|
| 506 |
+
path = "models/esm2_t30_150M_UR50D.pt"
|
| 507 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t30_150M_UR50D.pt"
|
| 508 |
+
sha256 = "881c7176cf198ef8dec26a3c375d40eb58d0c33df95c22562ca6cc6d3f812c62"
|
| 509 |
+
size = 592774773
|
| 510 |
+
|
| 511 |
+
[[models.oracle_assets]]
|
| 512 |
+
role = "contact_regression"
|
| 513 |
+
path = "regression/esm2_t30_150M_UR50D-contact-regression.pt"
|
| 514 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/regression/esm2_t30_150M_UR50D-contact-regression.pt"
|
| 515 |
+
sha256 = "6a604b96722ed052eef8a094ad90b275ba2e987d406315dbed0bdc6b3c4238a7"
|
| 516 |
+
size = 3431
|
| 517 |
+
|
| 518 |
+
[[models]]
|
| 519 |
+
id = "esm2_650m"
|
| 520 |
+
family = "esm2"
|
| 521 |
+
size_category = "large"
|
| 522 |
+
generation_contract = "not_applicable"
|
| 523 |
+
official_golden = { metadata = "tests/goldens/esm2_650m.json=sha256:f18332172fcb3abf5dd2485fd55f5b0d193ad3b93a44cc744e0d02817c927477", tensors = "tests/goldens/esm2_650m.safetensors=sha256:c3a66b75add03628e62e238cb63da6a9e4d321f8160e84bdf2a131c096977f86" }
|
| 524 |
+
fast_repo = "Synthyra/ESM2-650M"
|
| 525 |
+
fast_revision = "ca0718a5d52b80d5c60dd76860e55e061a95fb0a"
|
| 526 |
+
fast_files = [
|
| 527 |
+
"config.json=git-sha1:88f6bd240680b29c3244df8292246048401f5caf",
|
| 528 |
+
"model.safetensors=sha256:a15142e94ecf36f0edde9b37796f591e609ebe1694ca411e93640f0ee384994a",
|
| 529 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 530 |
+
"tokenizer_config.json=git-sha1:3cfc5db0c6790859a3bc2a4dc053a813acd65295",
|
| 531 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 532 |
+
]
|
| 533 |
+
official_repo = "facebook/esm2_t33_650M_UR50D"
|
| 534 |
+
official_revision = "08e4846e537177426273712802403f7ba8261b6c"
|
| 535 |
+
official_files = [
|
| 536 |
+
"config.json=git-sha1:a956a25d277f30bd870d3760b9a116f19ead885e",
|
| 537 |
+
"model.safetensors=sha256:a08adabb949fa67ad3c14b509d04fd60368b35007b0095e3358f81200c4f4db0",
|
| 538 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 539 |
+
"tokenizer_config.json=git-sha1:3f0d47e841e1cb75257aeaf76d156802899a217e",
|
| 540 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 541 |
+
]
|
| 542 |
+
|
| 543 |
+
[[models.oracle_assets]]
|
| 544 |
+
role = "weights"
|
| 545 |
+
path = "models/esm2_t33_650M_UR50D.pt"
|
| 546 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t33_650M_UR50D.pt"
|
| 547 |
+
sha256 = "ea9d0522b335a8778dea6535a65301f10208dece28cd5865482b0b1fc446168c"
|
| 548 |
+
size = 2604537549
|
| 549 |
+
|
| 550 |
+
[[models.oracle_assets]]
|
| 551 |
+
role = "contact_regression"
|
| 552 |
+
path = "regression/esm2_t33_650M_UR50D-contact-regression.pt"
|
| 553 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/regression/esm2_t33_650M_UR50D-contact-regression.pt"
|
| 554 |
+
sha256 = "8ffe6edbd4173dc8d45c2cd5cb27d43aad77ec26b4c768200c58ae1f96693575"
|
| 555 |
+
size = 3687
|
| 556 |
+
|
| 557 |
+
[[models]]
|
| 558 |
+
id = "esm2_3b"
|
| 559 |
+
family = "esm2"
|
| 560 |
+
size_category = "xlarge"
|
| 561 |
+
generation_contract = "not_applicable"
|
| 562 |
+
official_golden = { metadata = "tests/goldens/esm2_3b.json=sha256:5043b2333c57a34d54fac53916722d1acb4b6fd50395b9abafa805435b184a48", tensors = "tests/goldens/esm2_3b.safetensors=sha256:dfd5a8cb05d3e814a080185c4808c8e7ec2277f070f395562fcfbe4376789e4e" }
|
| 563 |
+
notes = "The pinned default SDPA BF16 path uses a checkpoint-specific numeric calibration: relative L2 target/hard limit 0.06/0.07, relative Q99.9 0.15/0.18, first-percentile residue cosine 0.994/0.992, and pooled cosine 0.998/0.997. Exact state identity and the global logits-distribution contract remain required."
|
| 564 |
+
fast_repo = "Synthyra/ESM2-3B"
|
| 565 |
+
fast_revision = "ff89d0180f414ab9c677219a25da79bf09185456"
|
| 566 |
+
fast_files = [
|
| 567 |
+
"config.json=git-sha1:94944ad6cabaa40a3ce1cbe6699cf464fdc1b2c0",
|
| 568 |
+
"model-00001-of-00003.safetensors=sha256:04b57854545c23779b562ee2ae22f10021ba0f4d586ba0ad482ee6eda187d562",
|
| 569 |
+
"model-00002-of-00003.safetensors=sha256:34954aaa05bc91635776ba6672946da5822626753d80db97b38c0538e9525102",
|
| 570 |
+
"model-00003-of-00003.safetensors=sha256:a6b3a55b9e3b2e1778de34c665c3dd17bdfdf6da9d6d5c97730c57168709ccae",
|
| 571 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 572 |
+
"tokenizer_config.json=git-sha1:3cfc5db0c6790859a3bc2a4dc053a813acd65295",
|
| 573 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 574 |
+
]
|
| 575 |
+
official_repo = "facebook/esm2_t36_3B_UR50D"
|
| 576 |
+
official_revision = "476b639933c8baad5ad09a60ac1a87f987b656fc"
|
| 577 |
+
official_files = [
|
| 578 |
+
"config.json=git-sha1:69e7563923f87d2d7439bfb83e5a19b44b46d71b",
|
| 579 |
+
"pytorch_model-00001-of-00002.bin=sha256:0f971f11c449d21422aa982b791619c10351972992c735f4c3cd43fe09790412",
|
| 580 |
+
"pytorch_model-00002-of-00002.bin=sha256:7560b46fc383c691fb74b915b7d4bcef40d3df181447f16ba4b298845e308d0c",
|
| 581 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 582 |
+
"tokenizer_config.json=git-sha1:3f0d47e841e1cb75257aeaf76d156802899a217e",
|
| 583 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 584 |
+
]
|
| 585 |
+
|
| 586 |
+
[[models.oracle_assets]]
|
| 587 |
+
role = "weights"
|
| 588 |
+
path = "models/esm2_t36_3B_UR50D.pt"
|
| 589 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t36_3B_UR50D.pt"
|
| 590 |
+
sha256 = "7de8b4082ba15891959ab368b77ce3886697af1efb16d3c9e9e7b0c5d3f07500"
|
| 591 |
+
size = 5678116398
|
| 592 |
+
|
| 593 |
+
[[models.oracle_assets]]
|
| 594 |
+
role = "contact_regression"
|
| 595 |
+
path = "regression/esm2_t36_3B_UR50D-contact-regression.pt"
|
| 596 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/regression/esm2_t36_3B_UR50D-contact-regression.pt"
|
| 597 |
+
sha256 = "4da500eab246481dc9c8c95bc7b1d02f2803d761c380b0e95186d4a07d0fc84e"
|
| 598 |
+
size = 6759
|
| 599 |
+
|
| 600 |
+
[[models]]
|
| 601 |
+
id = "esmc_small"
|
| 602 |
+
family = "esm_plusplus"
|
| 603 |
+
size_category = "medium"
|
| 604 |
+
generation_contract = "not_applicable"
|
| 605 |
+
official_golden = { metadata = "tests/goldens/esmc_small.json=sha256:bb02652cf3cc484756b98ffa4ba55ed4c55870d2cea3342adb1d920ba9dfe10a", tensors = "tests/goldens/esmc_small.safetensors=sha256:03378d0f0fdd8161178ebb2c1f0da1b9776a726c8e8d3a10c009808a24de5654" }
|
| 606 |
+
notes = "Release contract: SDPA must match the pinned Biohub implementation bit-for-bit across every hidden state, last hidden state, logits, special token, and padding position. Eager and FlashAttention 2 are release-gated in BF16 against the pinned boundary-length and biological panels with a relative-L2 engineering target of 0.029, hard limit of 0.03, relative-Q99.9 target of 0.049, first-percentile residue-cosine target of 0.997, and Jensen-Shannon target of 0.0004. The global pooled-cosine and top-1 thresholds remain unchanged. Flex Attention and FlashAttention 3 remain selectable as opt-in alternatives, but they are not strict-parity choices: on the locked H100 BF16 generated-boundary panel, ESMC-6B Flex Attention exceeds the 0.03 relative-L2 hard limit and FlashAttention 3 falls below the 0.995 residue-cosine hard limit. The deviation is consistent with backend-specific BF16 kernel arithmetic; it is not a weight-conversion difference or silent fallback. Use SDPA for exact Biohub parity or FlashAttention 2 for release-gated acceleration."
|
| 607 |
+
fast_repo = "Synthyra/ESMplusplus_small"
|
| 608 |
+
fast_revision = "46c5f7d562e47d4c14165b424c71ab7db008e6fb"
|
| 609 |
+
fast_files = [
|
| 610 |
+
"config.json=git-sha1:df2f44187157b0cc371c48c887b77b1783679201",
|
| 611 |
+
"model.safetensors=sha256:d099223765bc4f1ae8d6c7e18561ce41df1d54073fdc5327ef0a229235a8f52a",
|
| 612 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 613 |
+
"tokenizer.json=git-sha1:f49735e56cebab0e791aeaae777757b7fd114f71",
|
| 614 |
+
"tokenizer_config.json=git-sha1:2985ed2b8aa8ecfb1d12f53f47d2b8a44cc21756",
|
| 615 |
+
]
|
| 616 |
+
official_repo = "biohub/ESMC-300M"
|
| 617 |
+
official_revision = "a59b831785f907e96e6a246b1d142bfb76df31ee"
|
| 618 |
+
official_files = [
|
| 619 |
+
"config.json=git-sha1:9a49eacf4e65c39f74381f0f0d240e3b89ef43d7",
|
| 620 |
+
"model.safetensors=sha256:0772d8fe64bb25e14fe6f23b80e3c9a7d215d0da3c6cba5bd356d7c0e0bb22cc",
|
| 621 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 622 |
+
"tokenizer.json=git-sha1:81c797f56768b22dec0301fa771f018b7e43e98c",
|
| 623 |
+
"tokenizer_config.json=git-sha1:2238856624f8d39f03af53a2576c2d9b18c82f61",
|
| 624 |
+
]
|
| 625 |
+
|
| 626 |
+
[[models]]
|
| 627 |
+
id = "esmc_large"
|
| 628 |
+
family = "esm_plusplus"
|
| 629 |
+
size_category = "large"
|
| 630 |
+
generation_contract = "not_applicable"
|
| 631 |
+
official_golden = { metadata = "tests/goldens/esmc_large.json=sha256:7a4d614f67b6fde417f3fd89f61e7ec442ae284769734b2b73e14945a816a8fd", tensors = "tests/goldens/esmc_large.safetensors=sha256:e13302df4cf7e8381552f1043a8fd0f31f3e0d50b2ab6009fb86b7940ae8ff79" }
|
| 632 |
+
notes = "Release contract: SDPA must match the pinned Biohub implementation bit-for-bit across every hidden state, last hidden state, logits, special token, and padding position. Eager and FlashAttention 2 are release-gated in BF16 against the pinned boundary-length and biological panels with a relative-L2 engineering target of 0.029, hard limit of 0.03, relative-Q99.9 target of 0.049, first-percentile residue-cosine target of 0.997, and Jensen-Shannon target of 0.0004. The global pooled-cosine and top-1 thresholds remain unchanged. Flex Attention and FlashAttention 3 remain selectable as opt-in alternatives, but they are not strict-parity choices: on the locked H100 BF16 generated-boundary panel, ESMC-6B Flex Attention exceeds the 0.03 relative-L2 hard limit and FlashAttention 3 falls below the 0.995 residue-cosine hard limit. The deviation is consistent with backend-specific BF16 kernel arithmetic; it is not a weight-conversion difference or silent fallback. Use SDPA for exact Biohub parity or FlashAttention 2 for release-gated acceleration."
|
| 633 |
+
fast_repo = "Synthyra/ESMplusplus_large"
|
| 634 |
+
fast_revision = "f813401638b3fddab09748aec1ad2bf537aa4208"
|
| 635 |
+
fast_files = [
|
| 636 |
+
"config.json=git-sha1:5736371902fe5d04e2859be30ac7dbd31b271b25",
|
| 637 |
+
"model.safetensors=sha256:4aff3f8c5de68c4d3e3824eb2c478e4a47355d3f849f3c745e5c8a5ee6cff851",
|
| 638 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 639 |
+
"tokenizer.json=git-sha1:f49735e56cebab0e791aeaae777757b7fd114f71",
|
| 640 |
+
"tokenizer_config.json=git-sha1:2985ed2b8aa8ecfb1d12f53f47d2b8a44cc21756",
|
| 641 |
+
]
|
| 642 |
+
official_repo = "biohub/ESMC-600M"
|
| 643 |
+
official_revision = "a7e82012c83126b9eedb055fea9fa84b6c02f094"
|
| 644 |
+
official_files = [
|
| 645 |
+
"config.json=git-sha1:71c8241dc28a5fb636248267a0927c0242b264c1",
|
| 646 |
+
"model.safetensors=sha256:e4232c30fd35fe2f57051ec88a703996ac94520580b4b836894207a3d45d9ff8",
|
| 647 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 648 |
+
"tokenizer.json=git-sha1:81c797f56768b22dec0301fa771f018b7e43e98c",
|
| 649 |
+
"tokenizer_config.json=git-sha1:2238856624f8d39f03af53a2576c2d9b18c82f61",
|
| 650 |
+
]
|
| 651 |
+
|
| 652 |
+
[[models]]
|
| 653 |
+
id = "esmc_6b"
|
| 654 |
+
family = "esm_plusplus"
|
| 655 |
+
size_category = "xlarge"
|
| 656 |
+
generation_contract = "not_applicable"
|
| 657 |
+
official_golden = { metadata = "tests/goldens/esmc_6b.json=sha256:e229d938719782f280fab22dfc4c43e86109fdb0cc523631168c5a491afaace3", tensors = "tests/goldens/esmc_6b.safetensors=sha256:a948945e985c7deaca7be8b7eed09c0a9521a2af3f2b10fc2ec7a7d2a0f99ada" }
|
| 658 |
+
notes = "Release contract: SDPA must match the pinned Biohub implementation bit-for-bit across every hidden state, last hidden state, logits, special token, and padding position. Eager and FlashAttention 2 are release-gated in BF16 against the pinned boundary-length and biological panels with a relative-L2 engineering target of 0.029, hard limit of 0.03, relative-Q99.9 target of 0.049, first-percentile residue-cosine target of 0.997, and Jensen-Shannon target of 0.0004. The global pooled-cosine and top-1 thresholds remain unchanged. Flex Attention and FlashAttention 3 remain selectable as opt-in alternatives, but they are not strict-parity choices: on the locked H100 BF16 generated-boundary panel, ESMC-6B Flex Attention exceeds the 0.03 relative-L2 hard limit and FlashAttention 3 falls below the 0.995 residue-cosine hard limit. The deviation is consistent with backend-specific BF16 kernel arithmetic; it is not a weight-conversion difference or silent fallback. Use SDPA for exact Biohub parity or FlashAttention 2 for release-gated acceleration."
|
| 659 |
+
fast_repo = "Synthyra/ESMplusplus_6B"
|
| 660 |
+
fast_revision = "0d579cce3b0f09efa6b3baddf6cc3fd8c9b616c8"
|
| 661 |
+
fast_files = [
|
| 662 |
+
"config.json=git-sha1:e740cbcf211f2511c70c25a1ff6017a757ba7a69",
|
| 663 |
+
"model-00001-of-00006.safetensors=sha256:d30d18703453019f2d2d050866309888720c28eebc9a10307d1ddf3799e85a65",
|
| 664 |
+
"model-00002-of-00006.safetensors=sha256:b3d85378ab5023f4160a96e9c8cbd4cc6f78a771a83c856e88d48112f555bc13",
|
| 665 |
+
"model-00003-of-00006.safetensors=sha256:52595519b59349c5c6e373e6f5ca4a3d48ea6dde345f7e61e24766df5fab0e5b",
|
| 666 |
+
"model-00004-of-00006.safetensors=sha256:e46c6113c89c6f3e9b072c1bef02d763a625c37bcd8f9da2ed9363891c9a0758",
|
| 667 |
+
"model-00005-of-00006.safetensors=sha256:6d92cb2bf9791de644de2ae86f8523d802ac3b4aaabfff0716ab6c2b97f6fb14",
|
| 668 |
+
"model-00006-of-00006.safetensors=sha256:5fc1a8632490bb34162823c35d0d591337b9e4195b22cc0560741397a6e9d0b3",
|
| 669 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 670 |
+
"tokenizer.json=git-sha1:f49735e56cebab0e791aeaae777757b7fd114f71",
|
| 671 |
+
"tokenizer_config.json=git-sha1:2985ed2b8aa8ecfb1d12f53f47d2b8a44cc21756",
|
| 672 |
+
]
|
| 673 |
+
official_repo = "biohub/ESMC-6B"
|
| 674 |
+
official_revision = "45b0fa5d7fb06faefbd5e3b89bdcef35d564e79a"
|
| 675 |
+
official_files = [
|
| 676 |
+
"config.json=git-sha1:19f5fb09e4f630fb5b748a497183c22a87ec5102",
|
| 677 |
+
"model-00001-of-00006.safetensors=sha256:bd90149ff223e6ac1a0cac6147a5ae0df20d3a21df4f65356a1f19cd14f4aa8a",
|
| 678 |
+
"model-00002-of-00006.safetensors=sha256:f75e2144d8269fe2eb4b3e0823fb089b94f176d8024153e85b8fb573a42294fa",
|
| 679 |
+
"model-00003-of-00006.safetensors=sha256:f699f01ecc9691d9c6470492765fe54b8b5d2e9f277c139e89427433ffdfe0b2",
|
| 680 |
+
"model-00004-of-00006.safetensors=sha256:46add1b7be098bbfdc3073884851ba3057f1b33ea23a158b650a37007dabd13d",
|
| 681 |
+
"model-00005-of-00006.safetensors=sha256:1e1cb62f060a34e18f54a31a76683ef888b8cec59e73315f5b31d25d45a1f88c",
|
| 682 |
+
"model-00006-of-00006.safetensors=sha256:56c73e13ae96e777ce65eee99364056069ef93b646470f352f83c5f1037b1b18",
|
| 683 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 684 |
+
"tokenizer.json=git-sha1:81c797f56768b22dec0301fa771f018b7e43e98c",
|
| 685 |
+
"tokenizer_config.json=git-sha1:2238856624f8d39f03af53a2576c2d9b18c82f61",
|
| 686 |
+
]
|
| 687 |
+
|
| 688 |
+
[[models]]
|
| 689 |
+
id = "esm3_small"
|
| 690 |
+
family = "esm3"
|
| 691 |
+
tokenizer_source = "esmc_small"
|
| 692 |
+
size_category = "large"
|
| 693 |
+
generation_contract = "not_applicable"
|
| 694 |
+
official_golden = { metadata = "tests/goldens/esm3_small.json=sha256:5470e8596cbba0e2882647eccbc53c36d8b48b0f3947d1fe0bcea68da1078c32", tensors = "tests/goldens/esm3_small.safetensors=sha256:d957922f810c9ab4c557d80d5aaaf6a3aab79a5a45e4638012a634a4134803b1" }
|
| 695 |
+
fast_repo = "Synthyra/ESM3_small"
|
| 696 |
+
fast_revision = "7ddb5a740f9e5f93933eb6410c0ee8684bc63ec1"
|
| 697 |
+
fast_files = [
|
| 698 |
+
"config.json=git-sha1:60526e2fdd8af9d4fba17f323775458ef5a1a1f9",
|
| 699 |
+
"model-00001-of-00002.safetensors=sha256:a4c9b736c4c59d51180e966005a164859b47d5cd36e1f8ecdea619fbd34a0e92",
|
| 700 |
+
"model-00002-of-00002.safetensors=sha256:bea60e4e91b03bb00b6cedd29b07606b8543f0869fb74454af7b26e216d80d2b",
|
| 701 |
+
"special_tokens_map.json=git-sha1:c907ee1dc19b24241749b32d665c291c7e6e8e4b",
|
| 702 |
+
"tokenizer.json=git-sha1:f49735e56cebab0e791aeaae777757b7fd114f71",
|
| 703 |
+
"tokenizer_config.json=git-sha1:2985ed2b8aa8ecfb1d12f53f47d2b8a44cc21756",
|
| 704 |
+
]
|
| 705 |
+
official_repo = "biohub/esm3-sm-open-v1"
|
| 706 |
+
official_revision = "47f0545b2b6daf26a93439a3cd610f4f7f3d5478"
|
| 707 |
+
official_files = [
|
| 708 |
+
"config.json=git-sha1:0967ef424bce6791893e9a57bb952f80fd536e93",
|
| 709 |
+
"data/weights/esm3_function_decoder_v0.pth=sha256:f76d074efcaccfe21365a4fa96f212dadd66798e1e49d809ab7ffbe025d227c9",
|
| 710 |
+
"data/weights/esm3_sm_open_v1.pth=sha256:5ead5a135c658068db6a4f1b933e72d6110992c4668822e1c0e2dcc53e38acd9",
|
| 711 |
+
"data/weights/esm3_structure_decoder_v0.pth=sha256:3b726258a44274792b40ce7ea307e10c5da09936368a4ffa2970264d909da65b",
|
| 712 |
+
"data/weights/esm3_structure_encoder_v0.pth=sha256:467acbaee703ba3ccde6e75241a912a316952e5ff071355f85c1d33c68704f40",
|
| 713 |
+
]
|
| 714 |
+
|
| 715 |
+
[[models]]
|
| 716 |
+
id = "e1_150m"
|
| 717 |
+
family = "e1"
|
| 718 |
+
size_category = "small"
|
| 719 |
+
generation_contract = "not_applicable"
|
| 720 |
+
official_golden = { metadata = "tests/goldens/e1_150m.json=sha256:701a64a6ab1a2fec5a427555b6af96232526c15cb3d5b4dc7fb253ac8f20b922", tensors = "tests/goldens/e1_150m.safetensors=sha256:6558bc8f1a7b20629eaaaa6f72601d0c2cdb859a5dc13595549b1773b6e2de41" }
|
| 721 |
+
fast_repo = "Synthyra/Profluent-E1-150M"
|
| 722 |
+
fast_revision = "7c5f3bbf697226a2e0900db7a100f9201774a907"
|
| 723 |
+
fast_files = [
|
| 724 |
+
"config.json=git-sha1:562ef21e722ca708064fc3d54d25b731d4ac8171",
|
| 725 |
+
"model.safetensors=sha256:d779ed3a4e23799aafc932dc09c9963428d10aa7075999b5f8851b39c76b67f6",
|
| 726 |
+
]
|
| 727 |
+
official_repo = "Profluent-Bio/E1-150m"
|
| 728 |
+
official_revision = "c4dbfe827e4aa6ed7f95eaef50dc1e084f4d77dc"
|
| 729 |
+
official_files = [
|
| 730 |
+
"config.json=git-sha1:485e649199b46fe6ee7456bebf7aae9b3d4baeab",
|
| 731 |
+
"model.safetensors=sha256:ba2656339005e6598642836acfdafde480fecc7e145ce0058eb54adf572c3484",
|
| 732 |
+
]
|
| 733 |
+
|
| 734 |
+
[[models]]
|
| 735 |
+
id = "e1_300m"
|
| 736 |
+
family = "e1"
|
| 737 |
+
size_category = "medium"
|
| 738 |
+
generation_contract = "not_applicable"
|
| 739 |
+
official_golden = { metadata = "tests/goldens/e1_300m.json=sha256:d3478f3f5957a0e0377864074dde0107de890019f96cb63548ee17ffb8f3ec3a", tensors = "tests/goldens/e1_300m.safetensors=sha256:92778b9ef95a803ddc84b3e3ca764c59e045872a94bcff0eb0cd47647732c188" }
|
| 740 |
+
fast_repo = "Synthyra/Profluent-E1-300M"
|
| 741 |
+
fast_revision = "5ef52c0ad2ae2578f40622696b763523810e8e26"
|
| 742 |
+
fast_files = [
|
| 743 |
+
"config.json=git-sha1:f5c91498b76a3e3282a0d716d87738abb1a1b6c1",
|
| 744 |
+
"model.safetensors=sha256:9271c4176a8a2e0905a0bb769570ba1c2978fb999a87da92db4cf2b041224864",
|
| 745 |
+
]
|
| 746 |
+
official_repo = "Profluent-Bio/E1-300m"
|
| 747 |
+
official_revision = "5a2871c587eadbcc9237bc686ea45e5b4d28dfb3"
|
| 748 |
+
official_files = [
|
| 749 |
+
"config.json=git-sha1:918cb09e6e96d4719ed85951f38c693360f9cdb8",
|
| 750 |
+
"model.safetensors=sha256:31e09a2542f45b04e6ce4adafb3b657f21e2d56d12bf68fd2266b1576a80bc9b",
|
| 751 |
+
]
|
| 752 |
+
|
| 753 |
+
[[models]]
|
| 754 |
+
id = "e1_600m"
|
| 755 |
+
family = "e1"
|
| 756 |
+
size_category = "large"
|
| 757 |
+
generation_contract = "not_applicable"
|
| 758 |
+
official_golden = { metadata = "tests/goldens/e1_600m.json=sha256:914be191c28141c1f84535cdb69ead0588a2057bb19d46c5bc7f3891a3d6739e", tensors = "tests/goldens/e1_600m.safetensors=sha256:22ed8417a4651ded255099f6d15c63c2c40552e700d2b0470d1adfde3a39c513" }
|
| 759 |
+
fast_repo = "Synthyra/Profluent-E1-600M"
|
| 760 |
+
fast_revision = "6c8bf0ec83b0e0178677c528b101efffd0677742"
|
| 761 |
+
fast_files = [
|
| 762 |
+
"config.json=git-sha1:1d35c0b35b473259875fd29ee80167487a0d6afe",
|
| 763 |
+
"model.safetensors=sha256:793483b1b3411eab73fe5214b94d1424ca0545992dfac6889cfc0186af472363",
|
| 764 |
+
]
|
| 765 |
+
official_repo = "Profluent-Bio/E1-600m"
|
| 766 |
+
official_revision = "52d959fb87a609d15cf223a485127b29ed5c382a"
|
| 767 |
+
official_files = [
|
| 768 |
+
"config.json=git-sha1:8a0a439ed4201462bc01189c9f8b43523b257b5c",
|
| 769 |
+
"model.safetensors=sha256:cfc108d4b98baaa62932331b40be265eae39dc382595bc3cde4a5ab55db1bf7a",
|
| 770 |
+
]
|
| 771 |
+
|
| 772 |
+
[[models]]
|
| 773 |
+
id = "dplm_150m"
|
| 774 |
+
family = "dplm"
|
| 775 |
+
size_category = "small"
|
| 776 |
+
generation_contract = "required"
|
| 777 |
+
official_golden = { metadata = "tests/goldens/dplm_150m.json=sha256:3228551fe3bed951db9ec97347143ec4462ce7c221ac240b7ce7730948c1dc1f", tensors = "tests/goldens/dplm_150m.safetensors=sha256:392992235195beed97ab8359b90a2e11e52f4326606f99a471447bed81d146bd" }
|
| 778 |
+
fast_repo = "Synthyra/DPLM-150M"
|
| 779 |
+
fast_revision = "90ba742754151a774f3b7ed580170d0a76b3e69d"
|
| 780 |
+
fast_files = [
|
| 781 |
+
"config.json=git-sha1:117ac2c1222152ef378abaad1f605e18c4a18ab0",
|
| 782 |
+
"model.safetensors=sha256:8bac5ac767ceb8deb511b272d32883f811768d56cb25e920cea94ba9b979ca14",
|
| 783 |
+
"special_tokens_map.json=git-sha1:ef5f0f7d7baf4947564eafcf79972d272cd80a15",
|
| 784 |
+
"tokenizer_config.json=git-sha1:80100348e3f2b8ab05b59f3352ea7631685083cd",
|
| 785 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 786 |
+
]
|
| 787 |
+
official_repo = "airkingbd/dplm_150m"
|
| 788 |
+
official_revision = "49b7125a5d28c6418fcc2f3c4fe799352ac1488b"
|
| 789 |
+
official_files = [
|
| 790 |
+
"config.json=git-sha1:4910cb02f1840e9ac577026f601829604af58c74",
|
| 791 |
+
"pytorch_model.bin=sha256:ea4eaa99536b60ed76f945f71a1a5e604f08447ec3def5104a93ca6001a59961",
|
| 792 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 793 |
+
"tokenizer_config.json=git-sha1:dbcdd9fb2e742627ee310713615e0d7aeed0c34e",
|
| 794 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 795 |
+
]
|
| 796 |
+
|
| 797 |
+
[[models]]
|
| 798 |
+
id = "dplm_650m"
|
| 799 |
+
family = "dplm"
|
| 800 |
+
size_category = "large"
|
| 801 |
+
generation_contract = "required"
|
| 802 |
+
official_golden = { metadata = "tests/goldens/dplm_650m.json=sha256:bf58d0ce73aaac7e6fb1923ef3d9adad67122df2a3dd414c3229488ef9587a6d", tensors = "tests/goldens/dplm_650m.safetensors=sha256:073f0a6abea7e48f28c2d921ff8329a28e22627f01979277cb324908a01b3378" }
|
| 803 |
+
fast_repo = "Synthyra/DPLM-650M"
|
| 804 |
+
fast_revision = "05dc16d97c5c028aed924c9ed681cee4ab609760"
|
| 805 |
+
fast_files = [
|
| 806 |
+
"config.json=git-sha1:3537150eb87b213a676d5840548625e220b60e8b",
|
| 807 |
+
"model.safetensors=sha256:e27a47b8ec1c078b3fccb36542210e20f0380c88828db2ca9acf3d8a25048bd8",
|
| 808 |
+
"special_tokens_map.json=git-sha1:ef5f0f7d7baf4947564eafcf79972d272cd80a15",
|
| 809 |
+
"tokenizer_config.json=git-sha1:80100348e3f2b8ab05b59f3352ea7631685083cd",
|
| 810 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 811 |
+
]
|
| 812 |
+
official_repo = "airkingbd/dplm_650m"
|
| 813 |
+
official_revision = "7a7e651baa667d094aba05e9dc1cf52a3332110a"
|
| 814 |
+
official_files = [
|
| 815 |
+
"config.json=git-sha1:625574d625a4178ca6966e9545fee56026c0b634",
|
| 816 |
+
"pytorch_model.bin=sha256:db4e54343a89e7600f41c3aacbc593db1b0caee82ec28cab25ff2ae090eba39c",
|
| 817 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 818 |
+
"tokenizer_config.json=git-sha1:dbcdd9fb2e742627ee310713615e0d7aeed0c34e",
|
| 819 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 820 |
+
]
|
| 821 |
+
|
| 822 |
+
[[models]]
|
| 823 |
+
id = "dplm_3b"
|
| 824 |
+
family = "dplm"
|
| 825 |
+
size_category = "xlarge"
|
| 826 |
+
generation_contract = "required"
|
| 827 |
+
official_golden = { metadata = "tests/goldens/dplm_3b.json=sha256:a5b6df8b9c7b371976892ec1d6c45581a32ad3a6325c6c0a0b3267012848c8ed", tensors = "tests/goldens/dplm_3b.safetensors=sha256:75b0a0854fc391133920b0feaaeb8f69ab7568a88b3759627aca1556c4338c1e" }
|
| 828 |
+
fast_repo = "Synthyra/DPLM-3B"
|
| 829 |
+
fast_revision = "7d764dd3d70ecf1ac0e64693de64a0064aacac65"
|
| 830 |
+
fast_files = [
|
| 831 |
+
"config.json=git-sha1:7f5baf9426be06760c86882948b0f4af2e681e22",
|
| 832 |
+
"model-00001-of-00003.safetensors=sha256:37b54855d087ef3e7d883464ae9d5ea3127ec15a16c6323d91ad16a6b98305c9",
|
| 833 |
+
"model-00002-of-00003.safetensors=sha256:042604fefb05ea8c360a48416ce7ba662a4f90b176b4baf646c5c1814c35e6e8",
|
| 834 |
+
"model-00003-of-00003.safetensors=sha256:b9ae04012665163c3fc9781dd04fcd69738ac20c07e615e98fc4483fd2c4de45",
|
| 835 |
+
"special_tokens_map.json=git-sha1:ef5f0f7d7baf4947564eafcf79972d272cd80a15",
|
| 836 |
+
"tokenizer_config.json=git-sha1:80100348e3f2b8ab05b59f3352ea7631685083cd",
|
| 837 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 838 |
+
]
|
| 839 |
+
official_repo = "airkingbd/dplm_3b"
|
| 840 |
+
official_revision = "53849d4a7fe944ae0b9cf2bbc0d2cc0054795b51"
|
| 841 |
+
official_files = [
|
| 842 |
+
"config.json=git-sha1:f6206456e8c2f22ebe1d37fce3b5d50fd8073e68",
|
| 843 |
+
"pytorch_model-00001-of-00004.bin=sha256:0bcb86a115fe744ed686756db143f78851304e855e2f83cec58681c6080ced5f",
|
| 844 |
+
"pytorch_model-00002-of-00004.bin=sha256:daf3324f3be949e7dd1c3c84b28da7fec5151b1890cb0904e73427266856a06f",
|
| 845 |
+
"pytorch_model-00003-of-00004.bin=sha256:dbbeb7924a21059854f994931e23590b054aa000b10370a71c052c4aa36e9246",
|
| 846 |
+
"pytorch_model-00004-of-00004.bin=sha256:21c01740d091487db43446489d8a893dea1fcc6f2e1c1991ece13945f7ab4e07",
|
| 847 |
+
"special_tokens_map.json=git-sha1:ba0f9b53dbbf27934f7555e5d31e37bdea9317f1",
|
| 848 |
+
"tokenizer_config.json=git-sha1:dbcdd9fb2e742627ee310713615e0d7aeed0c34e",
|
| 849 |
+
"vocab.txt=git-sha1:6b946952cc35537226f07fd70957ee2f848880d2",
|
| 850 |
+
]
|
| 851 |
+
|
| 852 |
+
[[models]]
|
| 853 |
+
id = "dplm2_150m"
|
| 854 |
+
family = "dplm2"
|
| 855 |
+
size_category = "small"
|
| 856 |
+
generation_contract = "required"
|
| 857 |
+
official_golden = { metadata = "tests/goldens/dplm2_150m.json=sha256:d269de779ea1503de72c77e7b2e6224afc9797bd945b40c571ff6faec782e4aa", tensors = "tests/goldens/dplm2_150m.safetensors=sha256:17fc26600938ba5364b8ecb96750786d33e9f92bcd4ea4df3e12a389340748eb" }
|
| 858 |
+
artifact_source = "official"
|
| 859 |
+
canonical_state_sha256 = "82e1751f59052b8de72b082517557db47947e8d9b4ac2f11278369e6c0cbf001"
|
| 860 |
+
fast_repo = "Synthyra/DPLM2-150M"
|
| 861 |
+
fast_revision = "182745b8dc5661f898481a4fa60a7af9d53385c4"
|
| 862 |
+
fast_files = [
|
| 863 |
+
"config.json=git-sha1:07905a2e4327d27d073cd0390f140aec2976125a",
|
| 864 |
+
"model.safetensors=sha256:0a7751b3113027b1d9c966a5bda2d6ab831855de7aaa047b911731665a7c3cc6",
|
| 865 |
+
"special_tokens_map.json=git-sha1:e6378d20e897b8806734e65fd3ef9cf42a17631b",
|
| 866 |
+
"tokenizer_config.json=git-sha1:f2090783e3368b7323aa877e2b740e09f0862259",
|
| 867 |
+
"vocab.txt=git-sha1:9706a4277a5c39dc9b4ec7b283e8eb130ceaa7f2",
|
| 868 |
+
]
|
| 869 |
+
official_repo = "airkingbd/dplm2_150m"
|
| 870 |
+
official_revision = "3451d984d06497f835ed49634bd68c9dfb54d730"
|
| 871 |
+
official_files = [
|
| 872 |
+
"config.json=git-sha1:20f1e55c64fdc4d1d30f7b1df64b6167fa23dc7c",
|
| 873 |
+
"pytorch_model.bin=sha256:be7f5cf9e421f59fcc437e63ce1c7391099a314a4e9a4f10b8688785fa581238",
|
| 874 |
+
"special_tokens_map.json=git-sha1:eb760e9f49a55145bbe0c64922d4ec2d3de1692a",
|
| 875 |
+
"tokenizer_config.json=git-sha1:fc8c21760dcff173955afb106859e5f015d4f757",
|
| 876 |
+
"vocab.txt=git-sha1:e133a3abd4350ddc3fc62548e162c8df7e62cf37",
|
| 877 |
+
]
|
| 878 |
+
|
| 879 |
+
[[models]]
|
| 880 |
+
id = "dplm2_650m"
|
| 881 |
+
family = "dplm2"
|
| 882 |
+
size_category = "large"
|
| 883 |
+
generation_contract = "required"
|
| 884 |
+
official_golden = { metadata = "tests/goldens/dplm2_650m.json=sha256:d9a7548f9af657a72d441ca70f27379863724fcce8ddd3da4f672104b7bfb772", tensors = "tests/goldens/dplm2_650m.safetensors=sha256:c4e0e467c252c3ac813363d2d4b17a5e3bd99e75fad315e76d97689b4655ddac" }
|
| 885 |
+
artifact_source = "official"
|
| 886 |
+
canonical_state_sha256 = "cba76b6602d2258de9fffff953b608d93cb8ef4a9e89b0bbd27e160c81e78bb4"
|
| 887 |
+
fast_repo = "Synthyra/DPLM2-650M"
|
| 888 |
+
fast_revision = "b9d8527a9473a54954fa2764f590b9ea1b435bb2"
|
| 889 |
+
fast_files = [
|
| 890 |
+
"config.json=git-sha1:3e079579b214d48a09db57f2c60be6a1acea5baf",
|
| 891 |
+
"model.safetensors=sha256:92db08c7dbfd6c5e03fbfeaea3f36b09640ee794dcf5ea8d550527869a9f1d63",
|
| 892 |
+
"special_tokens_map.json=git-sha1:e6378d20e897b8806734e65fd3ef9cf42a17631b",
|
| 893 |
+
"tokenizer_config.json=git-sha1:f2090783e3368b7323aa877e2b740e09f0862259",
|
| 894 |
+
"vocab.txt=git-sha1:9706a4277a5c39dc9b4ec7b283e8eb130ceaa7f2",
|
| 895 |
+
]
|
| 896 |
+
official_repo = "airkingbd/dplm2_650m"
|
| 897 |
+
official_revision = "0bc69b644976c6680ab7e26669854d1979e8876e"
|
| 898 |
+
official_files = [
|
| 899 |
+
"config.json=git-sha1:4cce8d9dc212cdace0e20e89169790bcf199c158",
|
| 900 |
+
"pytorch_model.bin=sha256:8d6e08cc05e4858064a714013c74cc88c9caa2cc8b12c34605a3c24bcd877cfb",
|
| 901 |
+
"special_tokens_map.json=git-sha1:eb760e9f49a55145bbe0c64922d4ec2d3de1692a",
|
| 902 |
+
"tokenizer_config.json=git-sha1:fc8c21760dcff173955afb106859e5f015d4f757",
|
| 903 |
+
"vocab.txt=git-sha1:e133a3abd4350ddc3fc62548e162c8df7e62cf37",
|
| 904 |
+
]
|
| 905 |
+
|
| 906 |
+
[[models]]
|
| 907 |
+
id = "dplm2_3b"
|
| 908 |
+
family = "dplm2"
|
| 909 |
+
size_category = "xlarge"
|
| 910 |
+
# The pinned public sampler fails before generation because cls_token_id is None.
|
| 911 |
+
# State, tokenizer, and inference parity remain required for this checkpoint.
|
| 912 |
+
generation_contract = "official_unavailable"
|
| 913 |
+
official_golden = { metadata = "tests/goldens/dplm2_3b.json=sha256:d6e0e02af53b13cb129192f06e264758aa21c9ebf4ee82411cf67037082d2329", tensors = "tests/goldens/dplm2_3b.safetensors=sha256:838b11824d08f83bcb0c0b3268e579f3a87dbfb965370cfe5c3f8793b96b1964" }
|
| 914 |
+
notes = "The pinned official DPLM2-3B sampler fails before generation, so live generation equivalence cannot be established for this checkpoint. State, tokenizer, and inference parity remain required."
|
| 915 |
+
artifact_source = "official"
|
| 916 |
+
canonical_state_sha256 = "8c46ec09115dbe6cbfb91d94ab5e906369d57e27fe620a7741c6f8cb1b6ca890"
|
| 917 |
+
fast_repo = "Synthyra/DPLM2-3B"
|
| 918 |
+
fast_revision = "2a63babe8848abf5233d31bd55891dff8285fc50"
|
| 919 |
+
fast_files = [
|
| 920 |
+
"config.json=git-sha1:5932b1d501fed28b84614e0d2c1ecc4e89f10d6e",
|
| 921 |
+
"model-00001-of-00003.safetensors=sha256:2ff393f6e8df1568ce075d50de69ff4e5e9d9886e5ec47e43d6c24df23459be3",
|
| 922 |
+
"model-00002-of-00003.safetensors=sha256:feb3cea852c2aa849cc30783a984a97f0d076990ade6606cda5e38bf2a5a9621",
|
| 923 |
+
"model-00003-of-00003.safetensors=sha256:9be363ddb98436af20901981ffbed2f1097377424987f6c1baad27d512b62e71",
|
| 924 |
+
"special_tokens_map.json=git-sha1:e6378d20e897b8806734e65fd3ef9cf42a17631b",
|
| 925 |
+
"tokenizer_config.json=git-sha1:f2090783e3368b7323aa877e2b740e09f0862259",
|
| 926 |
+
"vocab.txt=git-sha1:9706a4277a5c39dc9b4ec7b283e8eb130ceaa7f2",
|
| 927 |
+
]
|
| 928 |
+
official_repo = "airkingbd/dplm2_3b"
|
| 929 |
+
official_revision = "9e77567926f98d1b997ea9131a8eeb035b9bf827"
|
| 930 |
+
official_files = [
|
| 931 |
+
"config.json=git-sha1:22d51ce44cd6da8d819e0d00566987bb51d74753",
|
| 932 |
+
"pytorch_model-00001-of-00004.bin=sha256:d8c641eae6bf891581ec64d543169891b093e296f5679ac75c695bcf596b4211",
|
| 933 |
+
"pytorch_model-00002-of-00004.bin=sha256:6478ad86ec5fef3d1d26580493af2d8666009d3ff884f3f88548080c8bbf94b5",
|
| 934 |
+
"pytorch_model-00003-of-00004.bin=sha256:dde8f88dac4a6355488c2fb433ee12cd69f1169950566624fba43684d4d99dc6",
|
| 935 |
+
"pytorch_model-00004-of-00004.bin=sha256:17ec0145152bc10e4dd3b4c2edff337979f6b99ee7c7bfd6cf4e6dbd7262d079",
|
| 936 |
+
"special_tokens_map.json=git-sha1:eb760e9f49a55145bbe0c64922d4ec2d3de1692a",
|
| 937 |
+
"tokenizer_config.json=git-sha1:fc8c21760dcff173955afb106859e5f015d4f757",
|
| 938 |
+
"vocab.txt=git-sha1:e133a3abd4350ddc3fc62548e162c8df7e62cf37",
|
| 939 |
+
]
|
| 940 |
+
|
| 941 |
+
[[models]]
|
| 942 |
+
id = "ankh_base"
|
| 943 |
+
family = "ankh"
|
| 944 |
+
size_category = "medium"
|
| 945 |
+
generation_contract = "required"
|
| 946 |
+
official_golden = { metadata = "tests/goldens/ankh_base.json=sha256:ebce8d7de821827ee995789c9b38d79252d3b2f76888130b0a8a7eedafaefe2b", tensors = "tests/goldens/ankh_base.safetensors=sha256:f0e78aa15d11749e0c64ff57f9e88c51cec6538a0adf8951f839df70cc708b65" }
|
| 947 |
+
notes = "ANKH parity covers the official encoder and sequence-to-sequence heads. AutoModelForMaskedLM exposes the separately named FastPLMs synthesized masked-LM extension and is not an official ANKH head."
|
| 948 |
+
artifact_source = "official"
|
| 949 |
+
canonical_state_sha256 = "cdd8d30d88e5bf41f44e1eef4470d8e46607aba5f7c7c805b06c035b89c8c16f"
|
| 950 |
+
fast_repo = "Synthyra/ANKH_base"
|
| 951 |
+
fast_revision = "7ec329aae8e3e174bf22a1eb9e0e9fcc12b53092"
|
| 952 |
+
fast_files = [
|
| 953 |
+
"config.json=git-sha1:7e1cbce6d08f9bb64eee4410899b1c6b4054f418",
|
| 954 |
+
"model.safetensors=sha256:b0d3473cac1bda90e39cde54f2abe86da1fc84f872c833ca3415672776dccb95",
|
| 955 |
+
"special_tokens_map.json=git-sha1:a2d8d626c31389a935e197fb94072e2414a6e7d1",
|
| 956 |
+
"tokenizer.json=git-sha1:0734d752d12d0f46ac96467fbceb1c4bfbeee0be",
|
| 957 |
+
"tokenizer_config.json=git-sha1:db0b80de72d3b16242b9eda74ed4663e39c65bcf",
|
| 958 |
+
]
|
| 959 |
+
official_repo = "ElnaggarLab/ankh-base"
|
| 960 |
+
official_revision = "d99cb6b966530dfc2ae96bc69d9255c2a07308b0"
|
| 961 |
+
official_files = [
|
| 962 |
+
"config.json=git-sha1:abd44a36b5469e9a7cb019e4059b5ac1392d8422",
|
| 963 |
+
"pytorch_model.bin=sha256:9b2a886374f0ff4a893f4e7a989deed76bb2458c8998bd5202ea8e97d92ddcc3",
|
| 964 |
+
"special_tokens_map.json=git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 965 |
+
"tokenizer.json=git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 966 |
+
"tokenizer_config.json=git-sha1:a8a872ae3441e7cc85ce19210dff1e4c5d2d7bd0",
|
| 967 |
+
]
|
| 968 |
+
|
| 969 |
+
[[models]]
|
| 970 |
+
id = "ankh_large"
|
| 971 |
+
family = "ankh"
|
| 972 |
+
size_category = "large"
|
| 973 |
+
generation_contract = "required"
|
| 974 |
+
official_golden = { metadata = "tests/goldens/ankh_large.json=sha256:59492518b021de5cfaea87d672c9448c8558e99a3443ba2cc7ab544963196ecb", tensors = "tests/goldens/ankh_large.safetensors=sha256:3fb8d3ac27716d15a9ea92aeef6acf2b977bcc887d9b535000539e523673459b" }
|
| 975 |
+
notes = "ANKH parity covers the official encoder and sequence-to-sequence heads. AutoModelForMaskedLM exposes the separately named FastPLMs synthesized masked-LM extension and is not an official ANKH head."
|
| 976 |
+
artifact_source = "official"
|
| 977 |
+
canonical_state_sha256 = "e498a2e9aea76ef784cbe3e596c6b3f5e9a40e209ad837f7e3207099e4d74483"
|
| 978 |
+
fast_repo = "Synthyra/ANKH_large"
|
| 979 |
+
fast_revision = "3be3df34140f49dc4e65bd1f247e3ce819e7fc59"
|
| 980 |
+
fast_files = [
|
| 981 |
+
"config.json=git-sha1:272509deedb527e5c2c95b0c269194a44148fdcc",
|
| 982 |
+
"model.safetensors=sha256:e70b8f9755ac6bfe95d18359060ae9fe38fac63b12a89a886c83349d1adbaa53",
|
| 983 |
+
"special_tokens_map.json=git-sha1:a2d8d626c31389a935e197fb94072e2414a6e7d1",
|
| 984 |
+
"tokenizer.json=git-sha1:0734d752d12d0f46ac96467fbceb1c4bfbeee0be",
|
| 985 |
+
"tokenizer_config.json=git-sha1:2bcaff2567826f5f51188b00600d2c6e7bcea56e",
|
| 986 |
+
]
|
| 987 |
+
official_repo = "ElnaggarLab/ankh-large"
|
| 988 |
+
official_revision = "74b371dbfa3ee0a05d32ae74df0c2e0b82d6b9a6"
|
| 989 |
+
official_files = [
|
| 990 |
+
"config.json=git-sha1:1abf33e52ee3d6be67d780ec57d32ac2b27b5306",
|
| 991 |
+
"pytorch_model.bin=sha256:517b6e8b279dedcb477af240b35c46bd6eb3307723eb281e60d4b2c8a87b889b",
|
| 992 |
+
"special_tokens_map.json=git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 993 |
+
"tokenizer.json=git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 994 |
+
"tokenizer_config.json=git-sha1:d7fe02ba6f2b18d9ccfa19ac129c9fdc9ec24d09",
|
| 995 |
+
]
|
| 996 |
+
|
| 997 |
+
[[models]]
|
| 998 |
+
id = "ankh2_large"
|
| 999 |
+
family = "ankh"
|
| 1000 |
+
size_category = "large"
|
| 1001 |
+
generation_contract = "required"
|
| 1002 |
+
official_golden = { metadata = "tests/goldens/ankh2_large.json=sha256:e8df38994ca1a1e0c598ace34a0b257b264937e4fdbb01bc41544985116b02a4", tensors = "tests/goldens/ankh2_large.safetensors=sha256:25fe1569f55c635fab8fa49c1d62a889a35a2a738bad921f5764a85b58fd4b5d" }
|
| 1003 |
+
notes = "ANKH parity covers the official encoder and sequence-to-sequence heads. AutoModelForMaskedLM exposes the separately named FastPLMs synthesized masked-LM extension and is not an official ANKH head."
|
| 1004 |
+
artifact_source = "official"
|
| 1005 |
+
canonical_state_sha256 = "597c4fe2fa8711f11a25317905f1d62fa92905e55fdd5c0a79614cd9c9d2bca3"
|
| 1006 |
+
fast_repo = "Synthyra/ANKH2_large"
|
| 1007 |
+
fast_revision = "392de5ed52bbfd73b45f545e378aaebcff096d0e"
|
| 1008 |
+
fast_files = [
|
| 1009 |
+
"config.json=git-sha1:66b6adc7215743a98a3229958bbd1c9c42b6108b",
|
| 1010 |
+
"model.safetensors=sha256:be8e6242388d93b51cd9719a0e32cfc17a2e804786570c795ba332197eccb915",
|
| 1011 |
+
"special_tokens_map.json=git-sha1:a2d8d626c31389a935e197fb94072e2414a6e7d1",
|
| 1012 |
+
"tokenizer.json=git-sha1:0734d752d12d0f46ac96467fbceb1c4bfbeee0be",
|
| 1013 |
+
"tokenizer_config.json=git-sha1:db0b80de72d3b16242b9eda74ed4663e39c65bcf",
|
| 1014 |
+
]
|
| 1015 |
+
official_repo = "ElnaggarLab/ankh2-ext2"
|
| 1016 |
+
official_revision = "aa9b9fa72288c47d9f618ce80c011e24b54e17a8"
|
| 1017 |
+
official_files = [
|
| 1018 |
+
"config.json=git-sha1:9286bed4ecbc4f7113024919d16ec9719b0c0748",
|
| 1019 |
+
"generation_config.json=git-sha1:91f792e452403d46e170e206f9e50be5ddef9b9a",
|
| 1020 |
+
"pytorch_model.bin=sha256:2df583f28f111276ee22a7b76007f4297e9a69766d60bccd9c8d7169c06ac606",
|
| 1021 |
+
"special_tokens_map.json=git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 1022 |
+
"tokenizer.json=git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 1023 |
+
"tokenizer_config.json=git-sha1:854e5db75dae8b1e9dd39c5bae80dae5508b3e25",
|
| 1024 |
+
]
|
| 1025 |
+
|
| 1026 |
+
[[models]]
|
| 1027 |
+
id = "ankh3_large"
|
| 1028 |
+
family = "ankh"
|
| 1029 |
+
size_category = "large"
|
| 1030 |
+
generation_contract = "required"
|
| 1031 |
+
official_golden = { metadata = "tests/goldens/ankh3_large.json=sha256:2e5bb05b3baa5baa78f61fef7d2a2c669b0da5dbfaf6b50b12abd3e17253a961", tensors = "tests/goldens/ankh3_large.safetensors=sha256:e5c494ac418e0a2fe7bdad1376676d48960d58ec9e044d19bfffccb8c3288513" }
|
| 1032 |
+
notes = "ANKH parity covers the official encoder and sequence-to-sequence heads. AutoModelForMaskedLM exposes the separately named FastPLMs synthesized masked-LM extension and is not an official ANKH head."
|
| 1033 |
+
artifact_source = "official"
|
| 1034 |
+
canonical_state_sha256 = "60acb7ef86e85dc0c51fc1edf4c8e69a0480049723b6b2c95e6e9faa720c112a"
|
| 1035 |
+
fast_repo = "Synthyra/ANKH3_large"
|
| 1036 |
+
fast_revision = "53600f175f328f986f43e55ca8ceb14935d337a4"
|
| 1037 |
+
fast_files = [
|
| 1038 |
+
"config.json=git-sha1:432b09625d44a2eeab679fddb7495d42b560b7f9",
|
| 1039 |
+
"model.safetensors=sha256:9f50f58cf5b3a537a0a41aa918695c3a26d7985dd0b2266642d6f86324c9e7a1",
|
| 1040 |
+
"special_tokens_map.json=git-sha1:1fc3a4d6d4282e5201cd7c30d5c0a6a8bfa04f82",
|
| 1041 |
+
"tokenizer.json=git-sha1:3d14291df2d6db3a183c5c4fe133afb330cc44cf",
|
| 1042 |
+
"tokenizer_config.json=git-sha1:2005fec00a7ae9a49e248a1ecefbbd81c56674d6",
|
| 1043 |
+
]
|
| 1044 |
+
official_repo = "ElnaggarLab/ankh3-large"
|
| 1045 |
+
official_revision = "2be091622e8a393f0ef21735070084123c874b6e"
|
| 1046 |
+
official_files = [
|
| 1047 |
+
"config.json=git-sha1:f5278f77d158cdd8a173df888e3ed365e84a80a3",
|
| 1048 |
+
"generation_config.json=git-sha1:5767cc0cacebfd06884eb27ae1c796d3ca829fd2",
|
| 1049 |
+
"pytorch_model.bin=sha256:26321a345e07a25b21c6c41b651c4db91b420892e52c0dcbc55bd7a8f510f95b",
|
| 1050 |
+
"special_tokens_map.json=git-sha1:d596919b7fa2a197edd441ec3ec4685ecacd2de4",
|
| 1051 |
+
"spiece.model=sha256:f2b5e1bbd110b71ca9b2878e1fcd3265610076ecc97bd696e8a745c9bacc54e0",
|
| 1052 |
+
"tokenizer.json=git-sha1:90f0c94b43c81496b3ca81e3ec1c092ef2dd7fca",
|
| 1053 |
+
"tokenizer_config.json=git-sha1:0e699eebfa778698473b4faf1e66ef363b93fb21",
|
| 1054 |
+
]
|
| 1055 |
+
|
| 1056 |
+
[[models]]
|
| 1057 |
+
id = "ankh3_xl"
|
| 1058 |
+
family = "ankh"
|
| 1059 |
+
size_category = "xlarge"
|
| 1060 |
+
generation_contract = "required"
|
| 1061 |
+
official_golden = { metadata = "tests/goldens/ankh3_xl.json=sha256:66bb12e033e4163be225d636108a479393228a4f5061015c8af114e766c3c486", tensors = "tests/goldens/ankh3_xl.safetensors=sha256:72d34567d0228cb6f1ee701c578ed4039fead4346e3f161a52e0e74df28dc8ae" }
|
| 1062 |
+
notes = "ANKH parity covers the official encoder and sequence-to-sequence heads. AutoModelForMaskedLM exposes the separately named FastPLMs synthesized masked-LM extension and is not an official ANKH head. The official PyTorch shard index is deliberately excluded: the builder verifies every declared source shard directly and writes a new canonical safetensors index."
|
| 1063 |
+
artifact_source = "official"
|
| 1064 |
+
canonical_state_sha256 = "dd2188e0d2ca65232135714eef6de394239734d843ddae4928c7398685d858e7"
|
| 1065 |
+
fast_repo = "Synthyra/ANKH3_xl"
|
| 1066 |
+
fast_revision = "3cbf2c22c4f7d67bf0bfcbdcd500f41723e91d29"
|
| 1067 |
+
fast_files = [
|
| 1068 |
+
"config.json=git-sha1:23f6d78ddcb3a031b88f876eaaf04c2fafaea46f",
|
| 1069 |
+
"model-00001-of-00003.safetensors=sha256:39bd8f75cf98a67cf04055399f9fc401198f6fc2896b112aba9fd9ec9df52ab9",
|
| 1070 |
+
"model-00002-of-00003.safetensors=sha256:9ff73233b39d2c200abb78e66b320c014ec61431bd6e1af36fb188a3cfa24c34",
|
| 1071 |
+
"model-00003-of-00003.safetensors=sha256:c13125c02dbcd7f07bd412e9e085f2bca6624d2f1f45fedc95fb777f53161cbe",
|
| 1072 |
+
"special_tokens_map.json=git-sha1:1fc3a4d6d4282e5201cd7c30d5c0a6a8bfa04f82",
|
| 1073 |
+
"tokenizer.json=git-sha1:3d14291df2d6db3a183c5c4fe133afb330cc44cf",
|
| 1074 |
+
"tokenizer_config.json=git-sha1:2005fec00a7ae9a49e248a1ecefbbd81c56674d6",
|
| 1075 |
+
]
|
| 1076 |
+
official_repo = "ElnaggarLab/ankh3-xl"
|
| 1077 |
+
official_revision = "e00113df5c95ef71df7ea3f5a73d56bd00e473a4"
|
| 1078 |
+
official_files = [
|
| 1079 |
+
"config.json=git-sha1:f8997040e8913df75fd2eebe71a2a8eb750ed0d0",
|
| 1080 |
+
"generation_config.json=git-sha1:91f792e452403d46e170e206f9e50be5ddef9b9a",
|
| 1081 |
+
"pytorch_model-00001-of-00003.bin=sha256:2c9793cbee16697cd4149debe07d3a27143e280f6e970fa46042aae820fea981",
|
| 1082 |
+
"pytorch_model-00002-of-00003.bin=sha256:31c5a860e414513c829ae52affb0970d7cef2c0545df2d6e1338b6806ab7174b",
|
| 1083 |
+
"pytorch_model-00003-of-00003.bin=sha256:055a853bdd3623db95a637935aa299427e837cd8ea69fc04708b0262508bec75",
|
| 1084 |
+
"special_tokens_map.json=git-sha1:d596919b7fa2a197edd441ec3ec4685ecacd2de4",
|
| 1085 |
+
"spiece.model=sha256:f2b5e1bbd110b71ca9b2878e1fcd3265610076ecc97bd696e8a745c9bacc54e0",
|
| 1086 |
+
"tokenizer.json=git-sha1:90f0c94b43c81496b3ca81e3ec1c092ef2dd7fca",
|
| 1087 |
+
"tokenizer_config.json=git-sha1:0e699eebfa778698473b4faf1e66ef363b93fb21",
|
| 1088 |
+
]
|
| 1089 |
+
|
| 1090 |
+
[[models]]
|
| 1091 |
+
id = "boltz2"
|
| 1092 |
+
family = "boltz2"
|
| 1093 |
+
size_category = "structure"
|
| 1094 |
+
generation_contract = "not_applicable"
|
| 1095 |
+
notes = "Boltz2 is provisional in FastPLMs 1.0. Exact configuration, the declared inference-core state, feature preparation, and seeded execution remain tested, but native-environment BF16 end-to-end inference currently exceeds the fixed numerical-equivalence limits. FastPLMs therefore does not claim official inference equivalence for this checkpoint yet. Work on that numerical gap continues independently of the ESM++ and ESMFold2 release gates."
|
| 1096 |
+
fast_repo = "Synthyra/Boltz2"
|
| 1097 |
+
fast_revision = "3b148fc5efea109c065ec82ba8683d024de7134e"
|
| 1098 |
+
fast_files = [
|
| 1099 |
+
"config.json=git-sha1:8682ccb12e177e73bc7a351ff7e3af484bfb6fac",
|
| 1100 |
+
"model.safetensors=sha256:5c863fd200a1613a0e311071e2ad73ab350635e3fd336e6822cf45c52cb960e5",
|
| 1101 |
+
]
|
| 1102 |
+
official_repo = "boltz-community/boltz-2"
|
| 1103 |
+
official_revision = "6fdef46d763fee7fbb83ca5501ccceff43b85607"
|
| 1104 |
+
official_files = [
|
| 1105 |
+
"boltz2_conf.ckpt=sha256:090e82ac8c92f5e943fa1b39e7410a44027bea7243c0bbb3caa67a77fc1428e1",
|
| 1106 |
+
"mols.tar=sha256:39e076d96dbec6b4e86982bbda16f3a53a2a60c9bdc17828d88f6f9a0c7d1fd7",
|
| 1107 |
+
]
|
| 1108 |
+
|
| 1109 |
+
[[models]]
|
| 1110 |
+
id = "esmfold"
|
| 1111 |
+
family = "esmfold"
|
| 1112 |
+
size_category = "structure"
|
| 1113 |
+
generation_contract = "not_applicable"
|
| 1114 |
+
official_golden = { metadata = "tests/goldens/esmfold.json=sha256:380b9a96168410717d1f698feaabb826b1606444cbdeec86c2ea06d9ffe8f186", tensors = "tests/goldens/esmfold.safetensors=sha256:873b1b325a43d8e0f35f355c8914a2a9fe611cc48763875e9e6a22e09ec9ebcb" }
|
| 1115 |
+
fast_repo = "Synthyra/FastESMFold"
|
| 1116 |
+
fast_revision = "b88c8cb50d19b2cf7ab4fee4b0a61f5e02da7823"
|
| 1117 |
+
fast_files = [
|
| 1118 |
+
"config.json=git-sha1:18e0091dcbf6140bf68924d53c4c8917b9cd90b1",
|
| 1119 |
+
"model-00001-of-00003.safetensors=sha256:36fab9e5c96d409b2a34a8b4f1273acac8c07f119c32c4fcfa7d47bbcd55b83c",
|
| 1120 |
+
"model-00002-of-00003.safetensors=sha256:34954aaa05bc91635776ba6672946da5822626753d80db97b38c0538e9525102",
|
| 1121 |
+
"model-00003-of-00003.safetensors=sha256:2f1178cda0e6cff3b1e158e1acc59c83e3f4fc46e246388a5127bc56b8d9c4f2",
|
| 1122 |
+
"special_tokens_map.json=git-sha1:53cd95604a28eb7e23da763c8da23f5006ab2179",
|
| 1123 |
+
"tokenizer_config.json=git-sha1:10213f69b51b4b38876a29271b8f908e853a5800",
|
| 1124 |
+
"vocab.txt=git-sha1:eee0a1fc93c82568f78f086550fbd7c591cf423a",
|
| 1125 |
+
]
|
| 1126 |
+
official_repo = "facebook/esmfold_v1"
|
| 1127 |
+
official_revision = "75a3841ee059df2bf4d56688166c8fb459ddd97a"
|
| 1128 |
+
official_files = [
|
| 1129 |
+
"config.json=git-sha1:1232d0aee4be551021d8e70e66ed2b062df917bf",
|
| 1130 |
+
"pytorch_model.bin=sha256:2ee07356b125d1e3e57503c204111fd7323347fc4735d41d3caac57c2a78e116",
|
| 1131 |
+
"special_tokens_map.json=git-sha1:121c8d54f8ea66cdf678f48b3cb37c05b4de5c0d",
|
| 1132 |
+
"tokenizer_config.json=git-sha1:aad24fba9f1bad2d74ed79d414ddcd60e6b0f812",
|
| 1133 |
+
"vocab.txt=git-sha1:9abfdf5472c0ed970648b683b86ab131256b3e42",
|
| 1134 |
+
]
|
| 1135 |
+
|
| 1136 |
+
[[models.oracle_assets]]
|
| 1137 |
+
role = "weights"
|
| 1138 |
+
path = "models/esmfold_3B_v1.pt"
|
| 1139 |
+
url = "https://dl.fbaipublicfiles.com/fair-esm/models/esmfold_3B_v1.pt"
|
| 1140 |
+
sha256 = "e9a52579027e77d2d2e0a18218e755821f395730e86624cab9413dc117f5ca62"
|
| 1141 |
+
size = 2771653574
|
| 1142 |
+
|
| 1143 |
+
[[models]]
|
| 1144 |
+
id = "esmfold2"
|
| 1145 |
+
family = "esmfold2"
|
| 1146 |
+
size_category = "structure"
|
| 1147 |
+
generation_contract = "not_applicable"
|
| 1148 |
+
msa_conditioning = true
|
| 1149 |
+
official_golden = { metadata = "tests/goldens/esmfold2.json=sha256:f6e0ed1ec400b9a0fcc817db51774be968dc454b7a32645a07c479e42423ab20", tensors = "tests/goldens/esmfold2.safetensors=sha256:e4d6be4344c528e26b13f79a9303549e3de7e582da195c0078db3ce957fad420" }
|
| 1150 |
+
fast_repo = "Synthyra/ESMFold2"
|
| 1151 |
+
fast_revision = "cd5a0927cec585a778d983b99a8db23d2e9b281e"
|
| 1152 |
+
fast_files = [
|
| 1153 |
+
"config.json=git-sha1:67e81ff571f393f0b630cd5a22398bd84979c030",
|
| 1154 |
+
"model.safetensors=sha256:138fd4350d6892b81ce6be7ff9bf5a93ae9d4d3751f46a27438a3f9f0dcefa0e",
|
| 1155 |
+
]
|
| 1156 |
+
official_repo = "biohub/ESMFold2"
|
| 1157 |
+
official_revision = "1ebf0e3481a5184eb6171d40615c79e384b48796"
|
| 1158 |
+
official_files = [
|
| 1159 |
+
"config.json=git-sha1:0300c084b990b2bd600efd9f538aa5de27109fea",
|
| 1160 |
+
"model.safetensors=sha256:138fd4350d6892b81ce6be7ff9bf5a93ae9d4d3751f46a27438a3f9f0dcefa0e",
|
| 1161 |
+
]
|
| 1162 |
+
|
| 1163 |
+
[[models]]
|
| 1164 |
+
id = "esmfold2_fast"
|
| 1165 |
+
family = "esmfold2"
|
| 1166 |
+
size_category = "structure"
|
| 1167 |
+
generation_contract = "not_applicable"
|
| 1168 |
+
msa_conditioning = false
|
| 1169 |
+
official_golden = { metadata = "tests/goldens/esmfold2_fast.json=sha256:091b004c0b330217b59c12acd6da3d6edaf91e48d95f6d5f40fc20399cef9478", tensors = "tests/goldens/esmfold2_fast.safetensors=sha256:6e2e1cd07401538b4d9df994f82abe7a5b38a01e8d1ee26681e1216d44a81990" }
|
| 1170 |
+
fast_repo = "Synthyra/ESMFold2-Fast"
|
| 1171 |
+
fast_revision = "407875bfcaa42552bfcb25acd67ee1888b790170"
|
| 1172 |
+
fast_files = [
|
| 1173 |
+
"config.json=git-sha1:62ccca15a416a5dcbd02cd6ce161f432c7b4de58",
|
| 1174 |
+
"model.safetensors=sha256:60ca19f2898188beba92944365f7b909efd9c99212f5018af75cc47cd9a6184a",
|
| 1175 |
+
]
|
| 1176 |
+
official_repo = "biohub/ESMFold2-Fast"
|
| 1177 |
+
official_revision = "b28d8ace5e05e61e5bec1e6820cfd3e221819d12"
|
| 1178 |
+
official_files = [
|
| 1179 |
+
"config.json=git-sha1:c0ca526090fa7f8342ee4666d56e7fe3a4b8cbb2",
|
| 1180 |
+
"model.safetensors=sha256:60ca19f2898188beba92944365f7b909efd9c99212f5018af75cc47cd9a6184a",
|
| 1181 |
+
]
|
| 1182 |
+
|
| 1183 |
+
[[models]]
|
| 1184 |
+
id = "esmfold2_experimental_cutoff2025"
|
| 1185 |
+
family = "esmfold2"
|
| 1186 |
+
size_category = "structure"
|
| 1187 |
+
generation_contract = "not_applicable"
|
| 1188 |
+
msa_conditioning = true
|
| 1189 |
+
official_golden = { metadata = "tests/goldens/esmfold2_experimental_cutoff2025.json=sha256:cfd0e35b2bc468a0dc4f614d3acfa2fce004f96e9ae2433256ed095b829d55cc", tensors = "tests/goldens/esmfold2_experimental_cutoff2025.safetensors=sha256:9347466bbe803b6f5dc82e3356ca6cbbf2c2edd8765f9fd273385bda255019f6" }
|
| 1190 |
+
fast_repo = "Synthyra/ESMFold2-Experimental-Cutoff2025"
|
| 1191 |
+
fast_revision = "632ff4a9e68f1de78ee956a613267bdcdb5b354d"
|
| 1192 |
+
fast_files = [
|
| 1193 |
+
"config.json=git-sha1:41119745d38bc5503a0212ad923e75211dec565f",
|
| 1194 |
+
"model.safetensors=sha256:01358c317428d38535e3db513cab177336fc0f7fab0d84002e64b7741d5181b3",
|
| 1195 |
+
]
|
| 1196 |
+
official_repo = "biohub/ESMFold2-Experimental-Cutoff2025"
|
| 1197 |
+
official_revision = "56f94f5c1069ecde17512c96928850518340d287"
|
| 1198 |
+
official_files = [
|
| 1199 |
+
"config.json=git-sha1:79ed0dc0f867b8f09bfa004d6f77397c2ab9b38d",
|
| 1200 |
+
"model.safetensors=sha256:01358c317428d38535e3db513cab177336fc0f7fab0d84002e64b7741d5181b3",
|
| 1201 |
+
]
|
| 1202 |
+
auto_map = { AutoConfig = "fastplms.models.esmfold2.configuration_esmfold2.ESMFold2Config", AutoModel = "fastplms.models.esmfold2.modeling_esmfold2_experimental.ESMFold2ExperimentalModel" }
|
| 1203 |
+
|
| 1204 |
+
[[models]]
|
| 1205 |
+
id = "esmfold2_experimental_fast_cutoff2025"
|
| 1206 |
+
family = "esmfold2"
|
| 1207 |
+
size_category = "structure"
|
| 1208 |
+
generation_contract = "not_applicable"
|
| 1209 |
+
msa_conditioning = false
|
| 1210 |
+
official_golden = { metadata = "tests/goldens/esmfold2_experimental_fast_cutoff2025.json=sha256:1d0b2da4f1579243f37ae04bd4b834b747005cd8e8e7665e00d088123c43afd9", tensors = "tests/goldens/esmfold2_experimental_fast_cutoff2025.safetensors=sha256:516e216d05d7e6bee59e77126d3e595e2bb7821929433f00c259c5d5241964bb" }
|
| 1211 |
+
fast_repo = "Synthyra/ESMFold2-Experimental-Fast-Cutoff2025"
|
| 1212 |
+
fast_revision = "8f022c2514a6c32692aaca078a8391d6bc6c4bac"
|
| 1213 |
+
fast_files = [
|
| 1214 |
+
"config.json=git-sha1:b9d39e941050179ca51faaed58cbbd77778c1143",
|
| 1215 |
+
"model.safetensors=sha256:4e903b740ad6ad704ec60881bfd593e0d6c874a630ffa0f0838276e0b665088f",
|
| 1216 |
+
]
|
| 1217 |
+
official_repo = "biohub/ESMFold2-Experimental-Fast-Cutoff2025"
|
| 1218 |
+
official_revision = "74b88548bf19688b8727432db0d698cb2e1d8783"
|
| 1219 |
+
official_files = [
|
| 1220 |
+
"config.json=git-sha1:0333d68ddb12ed2f066741dcb801142f466c0a2c",
|
| 1221 |
+
"model.safetensors=sha256:4e903b740ad6ad704ec60881bfd593e0d6c874a630ffa0f0838276e0b665088f",
|
| 1222 |
+
]
|
| 1223 |
+
auto_map = { AutoConfig = "fastplms.models.esmfold2.configuration_esmfold2.ESMFold2Config", AutoModel = "fastplms.models.esmfold2.modeling_esmfold2_experimental.ESMFold2ExperimentalModel" }
|
fastplms/models/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lazy model-family namespace for FastPLMs.
|
| 2 |
+
|
| 3 |
+
Model classes are resolved through Transformers AutoClasses and the typed
|
| 4 |
+
registry. Importing this package therefore does not load checkpoints, create
|
| 5 |
+
tokenizers, compile kernels, or initialize an accelerator runtime.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
__all__: tuple[str, ...] = ()
|
fastplms/models/ankh/__init__.py
ADDED
|
File without changes
|
fastplms/models/ankh/modeling_ankh.py
ADDED
|
@@ -0,0 +1,1627 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from collections.abc import Mapping, Sequence
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from numbers import Real
|
| 7 |
+
from typing import Any, ClassVar
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from tokenizers import pre_tokenizers
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
from transformers import (
|
| 14 |
+
AutoTokenizer,
|
| 15 |
+
PretrainedConfig,
|
| 16 |
+
PreTrainedModel,
|
| 17 |
+
T5ForConditionalGeneration,
|
| 18 |
+
)
|
| 19 |
+
from transformers.modeling_outputs import (
|
| 20 |
+
MaskedLMOutput,
|
| 21 |
+
ModelOutput,
|
| 22 |
+
SequenceClassifierOutput,
|
| 23 |
+
TokenClassifierOutput,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from fastplms.attention import (
|
| 28 |
+
AttentionBackend,
|
| 29 |
+
FastPLMsAttentionMixin,
|
| 30 |
+
bool_to_additive_mask,
|
| 31 |
+
get_attention_mask,
|
| 32 |
+
resolve_attention_backend,
|
| 33 |
+
resolve_attention_backend_for_call,
|
| 34 |
+
set_config_attn_implementation,
|
| 35 |
+
)
|
| 36 |
+
from fastplms.embeddings import (
|
| 37 |
+
EmbeddingBatch,
|
| 38 |
+
EmbeddingMixin,
|
| 39 |
+
select_hidden_state_embeddings,
|
| 40 |
+
)
|
| 41 |
+
from fastplms.models.ttt import FastPLMTestTimeTrainingMixin
|
| 42 |
+
except ModuleNotFoundError as error:
|
| 43 |
+
_COMPOSITE_REQUIRED_NAMES = (
|
| 44 |
+
"AttentionBackend",
|
| 45 |
+
"EmbeddingBatch",
|
| 46 |
+
"EmbeddingMixin",
|
| 47 |
+
"FastPLMsAttentionMixin",
|
| 48 |
+
"FastPLMTestTimeTrainingMixin",
|
| 49 |
+
"bool_to_additive_mask",
|
| 50 |
+
"get_attention_mask",
|
| 51 |
+
"resolve_attention_backend",
|
| 52 |
+
"resolve_attention_backend_for_call",
|
| 53 |
+
"select_hidden_state_embeddings",
|
| 54 |
+
"set_config_attn_implementation",
|
| 55 |
+
)
|
| 56 |
+
if error.name != "fastplms" or any(
|
| 57 |
+
name not in globals() for name in _COMPOSITE_REQUIRED_NAMES
|
| 58 |
+
):
|
| 59 |
+
raise
|
| 60 |
+
# Legacy flat Hub composites define every shared symbol above this block.
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# ---------------------------------------------------------------------------
|
| 64 |
+
# Output dataclasses
|
| 65 |
+
# ---------------------------------------------------------------------------
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class AnkhEncoderOutput(ModelOutput):
|
| 70 |
+
last_hidden_state: torch.Tensor | None = None
|
| 71 |
+
hidden_states: tuple[torch.Tensor, ...] | None = None
|
| 72 |
+
attentions: tuple[torch.Tensor, ...] | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class AnkhMaskedLMOutput(ModelOutput):
|
| 77 |
+
loss: torch.Tensor | None = None
|
| 78 |
+
logits: torch.Tensor | None = None
|
| 79 |
+
last_hidden_state: torch.Tensor | None = None
|
| 80 |
+
hidden_states: tuple[torch.Tensor, ...] | None = None
|
| 81 |
+
attentions: tuple[torch.Tensor, ...] | None = None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ---------------------------------------------------------------------------
|
| 85 |
+
# Config
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class FastAnkhConfig(PretrainedConfig):
|
| 90 |
+
model_type = "fast_ankh"
|
| 91 |
+
attribute_map: ClassVar[dict[str, str]] = {
|
| 92 |
+
"head_dim": "d_kv",
|
| 93 |
+
"hidden_size": "d_model",
|
| 94 |
+
"num_attention_heads": "num_heads",
|
| 95 |
+
"num_hidden_layers": "num_layers",
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
vocab_size: int = 144,
|
| 101 |
+
d_model: int = 768,
|
| 102 |
+
d_kv: int = 64,
|
| 103 |
+
d_ff: int = 3072,
|
| 104 |
+
num_heads: int = 12,
|
| 105 |
+
num_layers: int = 48,
|
| 106 |
+
num_decoder_layers: int | None = None,
|
| 107 |
+
relative_attention_num_buckets: int = 64,
|
| 108 |
+
relative_attention_max_distance: int = 128,
|
| 109 |
+
dense_act_fn: str = "gelu_new",
|
| 110 |
+
feed_forward_proj: str | None = None,
|
| 111 |
+
dropout_rate: float = 0.0,
|
| 112 |
+
layer_norm_epsilon: float = 1e-6,
|
| 113 |
+
initializer_factor: float = 1.0,
|
| 114 |
+
pad_token_id: int = 0,
|
| 115 |
+
eos_token_id: int = 1,
|
| 116 |
+
decoder_start_token_id: int | None = None,
|
| 117 |
+
use_cache: bool = True,
|
| 118 |
+
tie_word_embeddings: bool = True,
|
| 119 |
+
attn_backend: str | None = None,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
if feed_forward_proj is None:
|
| 123 |
+
feed_forward_proj = (
|
| 124 |
+
"gated-gelu" if dense_act_fn == "gelu_new" else f"gated-{dense_act_fn}"
|
| 125 |
+
)
|
| 126 |
+
if decoder_start_token_id is None:
|
| 127 |
+
decoder_start_token_id = pad_token_id
|
| 128 |
+
if isinstance(dropout_rate, bool) or not isinstance(dropout_rate, Real):
|
| 129 |
+
raise TypeError("dropout_rate must be a real number in [0, 1).")
|
| 130 |
+
dropout_rate = float(dropout_rate)
|
| 131 |
+
if not 0.0 <= dropout_rate < 1.0:
|
| 132 |
+
raise ValueError("dropout_rate must be in [0, 1).")
|
| 133 |
+
serialized_encoder_decoder = kwargs.pop("is_encoder_decoder", True)
|
| 134 |
+
if serialized_encoder_decoder is not True:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"FastAnkhConfig requires is_encoder_decoder=true to match the official "
|
| 137 |
+
"T5 configuration."
|
| 138 |
+
)
|
| 139 |
+
super().__init__(
|
| 140 |
+
pad_token_id=pad_token_id,
|
| 141 |
+
eos_token_id=eos_token_id,
|
| 142 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 143 |
+
is_encoder_decoder=True,
|
| 144 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 145 |
+
**kwargs,
|
| 146 |
+
)
|
| 147 |
+
self.vocab_size = vocab_size
|
| 148 |
+
self.d_model = d_model
|
| 149 |
+
self.d_kv = d_kv
|
| 150 |
+
self.d_ff = d_ff
|
| 151 |
+
self.num_heads = num_heads
|
| 152 |
+
self.num_layers = num_layers
|
| 153 |
+
self.num_decoder_layers = num_layers if num_decoder_layers is None else num_decoder_layers
|
| 154 |
+
self.relative_attention_num_buckets = relative_attention_num_buckets
|
| 155 |
+
self.relative_attention_max_distance = relative_attention_max_distance
|
| 156 |
+
self.dense_act_fn = dense_act_fn
|
| 157 |
+
self.feed_forward_proj = feed_forward_proj
|
| 158 |
+
self.is_gated_act = feed_forward_proj.startswith("gated-")
|
| 159 |
+
self.dropout_rate = dropout_rate
|
| 160 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 161 |
+
self.initializer_factor = initializer_factor
|
| 162 |
+
self.use_cache = use_cache
|
| 163 |
+
self.scale_decoder_outputs = tie_word_embeddings
|
| 164 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 165 |
+
self.attn_backend = attn_backend
|
| 166 |
+
|
| 167 |
+
def to_dict(self) -> dict[str, Any]:
|
| 168 |
+
output = super().to_dict()
|
| 169 |
+
return output
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
_TOKENIZER_LOAD_CONTEXT_KEYS = (
|
| 173 |
+
"cache_dir",
|
| 174 |
+
"force_download",
|
| 175 |
+
"local_files_only",
|
| 176 |
+
"proxies",
|
| 177 |
+
"subfolder",
|
| 178 |
+
"token",
|
| 179 |
+
"trust_remote_code",
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def configure_ankh_tokenizer(tokenizer: Any) -> Any:
|
| 184 |
+
"""Apply ANKH's residue-aware pre-tokenizer to a tokenizer instance.
|
| 185 |
+
|
| 186 |
+
The tokenizer files published by the official checkpoints use a leading
|
| 187 |
+
metaspace convention intended for natural-language text. Protein inputs
|
| 188 |
+
are already residue-delimited, so retaining that convention emits a
|
| 189 |
+
leading ``<unk>`` token. FastPLMs configures the fast tokenizer to split
|
| 190 |
+
raw residue strings and tight sentinel prompts without manufacturing a
|
| 191 |
+
whitespace token.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
backend = getattr(tokenizer, "backend_tokenizer", None)
|
| 195 |
+
if backend is None:
|
| 196 |
+
if getattr(tokenizer, "is_fast", None) is False:
|
| 197 |
+
raise TypeError(
|
| 198 |
+
"ANKH requires a fast tokenizer so its residue-aware pre-tokenizer "
|
| 199 |
+
"can be configured."
|
| 200 |
+
)
|
| 201 |
+
# Lightweight tokenizer doubles used by offline CPU contracts need not
|
| 202 |
+
# expose a Rust tokenizer backend.
|
| 203 |
+
return tokenizer
|
| 204 |
+
backend.pre_tokenizer = pre_tokenizers.Metaspace(
|
| 205 |
+
replacement="\u2581",
|
| 206 |
+
prepend_scheme="never",
|
| 207 |
+
split=True,
|
| 208 |
+
)
|
| 209 |
+
return tokenizer
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def normalize_ankh_sequence(sequence: str) -> str:
|
| 213 |
+
"""Return one ANKH protein sequence in canonical raw-residue form."""
|
| 214 |
+
|
| 215 |
+
if not isinstance(sequence, str):
|
| 216 |
+
raise TypeError("ANKH protein sequences must be strings.")
|
| 217 |
+
normalized = "".join(sequence.split())
|
| 218 |
+
if not normalized:
|
| 219 |
+
raise ValueError("ANKH protein sequences must not be empty or whitespace-only.")
|
| 220 |
+
return normalized
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def normalize_ankh_decoder_prompt(prompt: str) -> str:
|
| 224 |
+
"""Return a decoder prompt with residues and sentinels directly adjacent."""
|
| 225 |
+
|
| 226 |
+
if not isinstance(prompt, str):
|
| 227 |
+
raise TypeError("ANKH decoder prompts must be strings.")
|
| 228 |
+
normalized = "".join(prompt.split())
|
| 229 |
+
if not normalized:
|
| 230 |
+
raise ValueError("ANKH decoder prompts must not be empty or whitespace-only.")
|
| 231 |
+
return normalized
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _normalize_ankh_text_batch(
|
| 235 |
+
values: str | Sequence[str],
|
| 236 |
+
*,
|
| 237 |
+
field: str,
|
| 238 |
+
) -> str | list[str]:
|
| 239 |
+
normalizer = normalize_ankh_sequence if field == "sequence" else normalize_ankh_decoder_prompt
|
| 240 |
+
if isinstance(values, str):
|
| 241 |
+
return normalizer(values)
|
| 242 |
+
if isinstance(values, bytes) or not isinstance(values, Sequence):
|
| 243 |
+
raise TypeError(f"ANKH {field} inputs must be a string or a sequence of strings.")
|
| 244 |
+
return [normalizer(value) for value in values]
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def tokenize_ankh_sequences(
|
| 248 |
+
tokenizer: Any,
|
| 249 |
+
sequences: str | Sequence[str],
|
| 250 |
+
**tokenizer_kwargs: Any,
|
| 251 |
+
) -> Any:
|
| 252 |
+
"""Tokenize raw ANKH protein sequences with one model-wide contract."""
|
| 253 |
+
|
| 254 |
+
configured = configure_ankh_tokenizer(tokenizer)
|
| 255 |
+
normalized = _normalize_ankh_text_batch(sequences, field="sequence")
|
| 256 |
+
return configured(normalized, **tokenizer_kwargs)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def tokenize_ankh_decoder_prompts(
|
| 260 |
+
tokenizer: Any,
|
| 261 |
+
prompts: str | Sequence[str],
|
| 262 |
+
**tokenizer_kwargs: Any,
|
| 263 |
+
) -> Any:
|
| 264 |
+
"""Tokenize explicit ANKH decoder prompts without whitespace ``<unk>`` tokens."""
|
| 265 |
+
|
| 266 |
+
configured = configure_ankh_tokenizer(tokenizer)
|
| 267 |
+
normalized = _normalize_ankh_text_batch(prompts, field="decoder prompt")
|
| 268 |
+
return configured(normalized, **tokenizer_kwargs)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _load_ankh_tokenizer(
|
| 272 |
+
config: FastAnkhConfig,
|
| 273 |
+
load_context: Mapping[str, Any] | None = None,
|
| 274 |
+
):
|
| 275 |
+
"""Load the tokenizer from the same immutable checkpoint as the model."""
|
| 276 |
+
name_or_path = str(getattr(config, "_name_or_path", "")).strip()
|
| 277 |
+
if not name_or_path:
|
| 278 |
+
raise RuntimeError(
|
| 279 |
+
"ANKH tokenizer loading requires a model loaded with from_pretrained "
|
| 280 |
+
"so checkpoint provenance is available."
|
| 281 |
+
)
|
| 282 |
+
tokenizer_kwargs = {
|
| 283 |
+
key: value
|
| 284 |
+
for key, value in dict(load_context or {}).items()
|
| 285 |
+
if key in _TOKENIZER_LOAD_CONTEXT_KEYS and value is not None
|
| 286 |
+
}
|
| 287 |
+
# The resolved commit is authoritative. In particular, do not reload the
|
| 288 |
+
# tokenizer from a moving branch when Transformers resolved model weights to
|
| 289 |
+
# an immutable Hub commit.
|
| 290 |
+
revision = getattr(config, "_commit_hash", None)
|
| 291 |
+
if revision:
|
| 292 |
+
tokenizer_kwargs["revision"] = revision
|
| 293 |
+
tokenizer = AutoTokenizer.from_pretrained(name_or_path, **tokenizer_kwargs)
|
| 294 |
+
return configure_ankh_tokenizer(tokenizer)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class _AnkhTokenizerLoadMixin:
|
| 298 |
+
"""Keep tokenizer loading scoped to the model instance and weight request."""
|
| 299 |
+
|
| 300 |
+
@classmethod
|
| 301 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 302 |
+
load_context = {key: kwargs[key] for key in _TOKENIZER_LOAD_CONTEXT_KEYS if key in kwargs}
|
| 303 |
+
loaded = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 304 |
+
model = loaded[0] if isinstance(loaded, tuple) else loaded
|
| 305 |
+
model.__dict__["_fastplms_tokenizer_load_context"] = load_context
|
| 306 |
+
model.__dict__["_fastplms_tokenizer"] = None
|
| 307 |
+
return loaded
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def tokenizer(self):
|
| 311 |
+
tokenizer = self.__dict__.get("_fastplms_tokenizer")
|
| 312 |
+
if tokenizer is None:
|
| 313 |
+
tokenizer = _load_ankh_tokenizer(
|
| 314 |
+
self.config,
|
| 315 |
+
self.__dict__.get("_fastplms_tokenizer_load_context"),
|
| 316 |
+
)
|
| 317 |
+
self.__dict__["_fastplms_tokenizer"] = tokenizer
|
| 318 |
+
return tokenizer
|
| 319 |
+
|
| 320 |
+
@tokenizer.setter
|
| 321 |
+
def tokenizer(self, value) -> None:
|
| 322 |
+
self.__dict__["_fastplms_tokenizer"] = configure_ankh_tokenizer(value)
|
| 323 |
+
|
| 324 |
+
def _tokenize_sequence_batch(
|
| 325 |
+
self,
|
| 326 |
+
sequences: Sequence[str],
|
| 327 |
+
*,
|
| 328 |
+
tokenizer: Any | None = None,
|
| 329 |
+
**tokenizer_kwargs: Any,
|
| 330 |
+
) -> Any:
|
| 331 |
+
resolved_tokenizer = tokenizer if tokenizer is not None else self.tokenizer
|
| 332 |
+
return tokenize_ankh_sequences(
|
| 333 |
+
resolved_tokenizer,
|
| 334 |
+
sequences,
|
| 335 |
+
**tokenizer_kwargs,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
def embed_dataset(self, inputs: Any, **kwargs: Any) -> Any:
|
| 339 |
+
explicit_tokenizer = kwargs.get("tokenizer")
|
| 340 |
+
if explicit_tokenizer is not None:
|
| 341 |
+
kwargs["tokenizer"] = configure_ankh_tokenizer(explicit_tokenizer)
|
| 342 |
+
decoder_inputs = kwargs.get("decoder_inputs")
|
| 343 |
+
if (
|
| 344 |
+
decoder_inputs is not None
|
| 345 |
+
and not isinstance(decoder_inputs, (str, bytes))
|
| 346 |
+
and isinstance(decoder_inputs, Sequence)
|
| 347 |
+
):
|
| 348 |
+
kwargs["decoder_inputs"] = [
|
| 349 |
+
normalize_ankh_decoder_prompt(value) for value in decoder_inputs
|
| 350 |
+
]
|
| 351 |
+
return EmbeddingMixin.embed_dataset(self, inputs, **kwargs)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _validate_hidden_state_source(hidden_state_source: str) -> str:
|
| 355 |
+
if hidden_state_source not in {"encoder", "decoder"}:
|
| 356 |
+
raise ValueError(
|
| 357 |
+
"hidden_state_source must be either 'encoder' or 'decoder'; "
|
| 358 |
+
f"received {hidden_state_source!r}."
|
| 359 |
+
)
|
| 360 |
+
return hidden_state_source
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _require_encoder_embedding_source(
|
| 364 |
+
hidden_state_source: str,
|
| 365 |
+
*,
|
| 366 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 367 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 368 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 369 |
+
) -> None:
|
| 370 |
+
source = _validate_hidden_state_source(hidden_state_source)
|
| 371 |
+
if source == "decoder":
|
| 372 |
+
raise ValueError(
|
| 373 |
+
"Decoder hidden states require FastAnkhForConditionalGeneration loaded "
|
| 374 |
+
"through AutoModelForSeq2SeqLM; the encoder-only ANKH view does not "
|
| 375 |
+
"allocate a decoder."
|
| 376 |
+
)
|
| 377 |
+
decoder_values = (decoder_inputs, decoder_input_ids, decoder_attention_mask)
|
| 378 |
+
if any(value is not None for value in decoder_values):
|
| 379 |
+
raise ValueError(
|
| 380 |
+
"decoder_inputs, decoder_input_ids, and decoder_attention_mask are only "
|
| 381 |
+
"valid when hidden_state_source='decoder'."
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _biological_token_mask(
|
| 386 |
+
input_ids: torch.Tensor,
|
| 387 |
+
attention_mask: torch.Tensor,
|
| 388 |
+
tokenizer: Any,
|
| 389 |
+
) -> torch.Tensor:
|
| 390 |
+
mask = attention_mask.to(device=input_ids.device, dtype=torch.bool)
|
| 391 |
+
special_ids = tuple(int(value) for value in getattr(tokenizer, "all_special_ids", ()))
|
| 392 |
+
if special_ids:
|
| 393 |
+
mask = mask & ~torch.isin(
|
| 394 |
+
input_ids,
|
| 395 |
+
torch.tensor(special_ids, device=input_ids.device, dtype=input_ids.dtype),
|
| 396 |
+
)
|
| 397 |
+
return mask
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# ---------------------------------------------------------------------------
|
| 401 |
+
# Submodules
|
| 402 |
+
# ---------------------------------------------------------------------------
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class AnkhRMSNorm(nn.Module):
|
| 406 |
+
"""T5-style RMS layer norm: scales without mean subtraction or bias."""
|
| 407 |
+
|
| 408 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
| 409 |
+
super().__init__()
|
| 410 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 411 |
+
self.variance_epsilon = eps
|
| 412 |
+
|
| 413 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 414 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 415 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 416 |
+
return self.weight * hidden_states.to(self.weight.dtype)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _gelu_new(x: torch.Tensor) -> torch.Tensor:
|
| 420 |
+
return (
|
| 421 |
+
0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class AnkhGatedFFN(nn.Module):
|
| 426 |
+
"""T5-style gated feed-forward: activation(wi_0(x)) * wi_1(x) -> wo."""
|
| 427 |
+
|
| 428 |
+
def __init__(self, config: FastAnkhConfig):
|
| 429 |
+
super().__init__()
|
| 430 |
+
self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 431 |
+
self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 432 |
+
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 433 |
+
self.act = F.silu if config.dense_act_fn == "silu" else _gelu_new
|
| 434 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 435 |
+
|
| 436 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 437 |
+
hidden_states = self.act(self.wi_0(hidden_states)) * self.wi_1(hidden_states)
|
| 438 |
+
return self.wo(self.dropout(hidden_states))
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
# ---------------------------------------------------------------------------
|
| 442 |
+
# Attention
|
| 443 |
+
# ---------------------------------------------------------------------------
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class AnkhSelfAttention(nn.Module):
|
| 447 |
+
"""T5-style self-attention with relative position bias and multi-backend dispatch.
|
| 448 |
+
|
| 449 |
+
Only layer 0 has ``has_relative_attention_bias=True`` and owns the
|
| 450 |
+
``nn.Embedding`` that produces the position bias. All other layers
|
| 451 |
+
receive the precomputed bias through the forward call.
|
| 452 |
+
"""
|
| 453 |
+
|
| 454 |
+
def __init__(self, config: FastAnkhConfig, has_relative_attention_bias: bool = False):
|
| 455 |
+
super().__init__()
|
| 456 |
+
self.num_heads = config.num_heads
|
| 457 |
+
self.d_kv = config.d_kv
|
| 458 |
+
self.inner_dim = self.num_heads * self.d_kv
|
| 459 |
+
self.has_relative_attention_bias = has_relative_attention_bias
|
| 460 |
+
self.relative_attention_num_buckets = config.relative_attention_num_buckets
|
| 461 |
+
self.relative_attention_max_distance = config.relative_attention_max_distance
|
| 462 |
+
|
| 463 |
+
self.q = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 464 |
+
self.k = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 465 |
+
self.v = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 466 |
+
self.o = nn.Linear(self.inner_dim, config.d_model, bias=False)
|
| 467 |
+
# T5/ANKH attention is unscaled: scores = Q K^T (no 1/sqrt(d_kv)).
|
| 468 |
+
# The learned relative position bias absorbs any temperature.
|
| 469 |
+
self.scale = 1.0
|
| 470 |
+
self.dropout_prob = float(config.dropout_rate)
|
| 471 |
+
|
| 472 |
+
if self.has_relative_attention_bias:
|
| 473 |
+
self.relative_attention_bias = nn.Embedding(
|
| 474 |
+
config.relative_attention_num_buckets, config.num_heads
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
self.attn_backend: AttentionBackend = AttentionBackend.SDPA # set by encoder
|
| 478 |
+
|
| 479 |
+
# ---- T5 relative position bucketing ----
|
| 480 |
+
|
| 481 |
+
@staticmethod
|
| 482 |
+
def _relative_position_bucket(
|
| 483 |
+
relative_position: torch.Tensor,
|
| 484 |
+
num_buckets: int = 32,
|
| 485 |
+
max_distance: int = 128,
|
| 486 |
+
) -> torch.Tensor:
|
| 487 |
+
"""Bidirectional log-bucketed relative position mapping (T5 style)."""
|
| 488 |
+
# Bidirectional: half buckets for negative, half for positive
|
| 489 |
+
num_buckets //= 2
|
| 490 |
+
relative_buckets = (relative_position > 0).to(torch.long) * num_buckets
|
| 491 |
+
relative_position = torch.abs(relative_position)
|
| 492 |
+
|
| 493 |
+
max_exact = num_buckets // 2
|
| 494 |
+
is_small = relative_position < max_exact
|
| 495 |
+
|
| 496 |
+
relative_position_if_large = max_exact + (
|
| 497 |
+
torch.log(relative_position.float() / max_exact)
|
| 498 |
+
/ math.log(max_distance / max_exact)
|
| 499 |
+
* (num_buckets - max_exact)
|
| 500 |
+
).to(torch.long)
|
| 501 |
+
relative_position_if_large = torch.clamp(relative_position_if_large, max=num_buckets - 1)
|
| 502 |
+
|
| 503 |
+
relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
|
| 504 |
+
return relative_buckets
|
| 505 |
+
|
| 506 |
+
def compute_bias(
|
| 507 |
+
self, query_length: int, key_length: int, device: torch.device
|
| 508 |
+
) -> torch.Tensor:
|
| 509 |
+
"""Compute the position-bias tensor A with shape (1, h, q, k)."""
|
| 510 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
| 511 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
| 512 |
+
relative_position = memory_position - context_position
|
| 513 |
+
buckets = self._relative_position_bucket(
|
| 514 |
+
relative_position,
|
| 515 |
+
num_buckets=self.relative_attention_num_buckets,
|
| 516 |
+
max_distance=self.relative_attention_max_distance,
|
| 517 |
+
)
|
| 518 |
+
values = self.relative_attention_bias(buckets) # A has shape (q, k, h).
|
| 519 |
+
return values.permute(2, 0, 1).unsqueeze(0) # A has shape (1, h, q, k).
|
| 520 |
+
|
| 521 |
+
# ---- Forward ----
|
| 522 |
+
|
| 523 |
+
def forward(
|
| 524 |
+
self,
|
| 525 |
+
hidden_states: torch.Tensor,
|
| 526 |
+
attention_mask_4d: torch.Tensor | None = None,
|
| 527 |
+
position_bias: torch.Tensor | None = None,
|
| 528 |
+
output_attentions: bool = False,
|
| 529 |
+
effective_backend: AttentionBackend | None = None,
|
| 530 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 531 |
+
"""Returns (attn_output, attn_weights_or_none, position_bias)."""
|
| 532 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
| 533 |
+
hidden_shape = (batch_size, seq_length, self.num_heads, self.d_kv)
|
| 534 |
+
|
| 535 |
+
query_heads = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 536 |
+
key_heads = self.k(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 537 |
+
value_heads = self.v(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 538 |
+
|
| 539 |
+
# The first layer computes the bias once; later layers reuse it.
|
| 540 |
+
if position_bias is None and self.has_relative_attention_bias:
|
| 541 |
+
position_bias = self.compute_bias(seq_length, seq_length, hidden_states.device)
|
| 542 |
+
# Fold padding mask into position bias so layers don't need separate mask.
|
| 543 |
+
if attention_mask_4d is not None:
|
| 544 |
+
position_bias = position_bias + bool_to_additive_mask(
|
| 545 |
+
attention_mask_4d, position_bias.dtype
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
if effective_backend is None:
|
| 549 |
+
effective_backend = resolve_attention_backend_for_call(
|
| 550 |
+
self.attn_backend,
|
| 551 |
+
output_attentions=output_attentions,
|
| 552 |
+
)
|
| 553 |
+
if output_attentions:
|
| 554 |
+
attn_output, attn_weights = self._manual_attn(
|
| 555 |
+
query_heads, key_heads, value_heads, position_bias
|
| 556 |
+
)
|
| 557 |
+
return self.o(attn_output), attn_weights, position_bias
|
| 558 |
+
|
| 559 |
+
if effective_backend == AttentionBackend.EAGER:
|
| 560 |
+
attn_output, _ = self._manual_attn(query_heads, key_heads, value_heads, position_bias)
|
| 561 |
+
elif effective_backend == AttentionBackend.SDPA:
|
| 562 |
+
attn_output = self._sdpa_attn(query_heads, key_heads, value_heads, position_bias)
|
| 563 |
+
else:
|
| 564 |
+
raise AssertionError(f"Unsupported backend for ANKH: {effective_backend}")
|
| 565 |
+
|
| 566 |
+
return self.o(attn_output), None, position_bias
|
| 567 |
+
|
| 568 |
+
def _sdpa_attn(
|
| 569 |
+
self,
|
| 570 |
+
query_heads: torch.Tensor,
|
| 571 |
+
key_heads: torch.Tensor,
|
| 572 |
+
value_heads: torch.Tensor,
|
| 573 |
+
position_bias: torch.Tensor | None,
|
| 574 |
+
) -> torch.Tensor:
|
| 575 |
+
# A is the additive position bias with shape (1, h, q, k), including padding.
|
| 576 |
+
# Never mutate torch.backends.cuda process-global reduction policy from
|
| 577 |
+
# a model forward. Concurrent model requests must not change each
|
| 578 |
+
# other's numerical behavior or restore a stale process setting.
|
| 579 |
+
context_heads = F.scaled_dot_product_attention(
|
| 580 |
+
query_heads,
|
| 581 |
+
key_heads,
|
| 582 |
+
value_heads,
|
| 583 |
+
attn_mask=position_bias,
|
| 584 |
+
dropout_p=self.dropout_prob if self.training else 0.0,
|
| 585 |
+
scale=self.scale,
|
| 586 |
+
)
|
| 587 |
+
return (
|
| 588 |
+
context_heads.transpose(1, 2)
|
| 589 |
+
.contiguous()
|
| 590 |
+
.view(query_heads.shape[0], -1, self.inner_dim)
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
def _manual_attn(
|
| 594 |
+
self,
|
| 595 |
+
query_heads: torch.Tensor,
|
| 596 |
+
key_heads: torch.Tensor,
|
| 597 |
+
value_heads: torch.Tensor,
|
| 598 |
+
position_bias: torch.Tensor | None,
|
| 599 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 600 |
+
attn_weights = torch.matmul(query_heads, key_heads.transpose(-1, -2)) * self.scale
|
| 601 |
+
if position_bias is not None:
|
| 602 |
+
attn_weights = attn_weights + position_bias
|
| 603 |
+
attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(attn_weights)
|
| 604 |
+
if self.dropout_prob > 0 and self.training:
|
| 605 |
+
attn_weights = F.dropout(
|
| 606 |
+
attn_weights,
|
| 607 |
+
p=self.dropout_prob,
|
| 608 |
+
training=self.training,
|
| 609 |
+
)
|
| 610 |
+
context_heads = torch.matmul(attn_weights, value_heads)
|
| 611 |
+
attn_output = (
|
| 612 |
+
context_heads.transpose(1, 2)
|
| 613 |
+
.contiguous()
|
| 614 |
+
.view(query_heads.shape[0], -1, self.inner_dim)
|
| 615 |
+
)
|
| 616 |
+
return attn_output, attn_weights
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
# ---------------------------------------------------------------------------
|
| 620 |
+
# Encoder block & stack (T5-compatible key naming)
|
| 621 |
+
# ---------------------------------------------------------------------------
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
class AnkhSelfAttentionLayer(nn.Module):
|
| 625 |
+
"""Wraps AnkhSelfAttention + layer_norm to match T5Block.layer[0] key naming."""
|
| 626 |
+
|
| 627 |
+
def __init__(self, config: FastAnkhConfig, has_relative_attention_bias: bool = False):
|
| 628 |
+
super().__init__()
|
| 629 |
+
self.SelfAttention = AnkhSelfAttention(config, has_relative_attention_bias)
|
| 630 |
+
self.layer_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 631 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 632 |
+
|
| 633 |
+
def forward(
|
| 634 |
+
self,
|
| 635 |
+
hidden_states: torch.Tensor,
|
| 636 |
+
attention_mask_4d: torch.Tensor | None = None,
|
| 637 |
+
position_bias: torch.Tensor | None = None,
|
| 638 |
+
output_attentions: bool = False,
|
| 639 |
+
effective_backend: AttentionBackend | None = None,
|
| 640 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 641 |
+
normed = self.layer_norm(hidden_states)
|
| 642 |
+
attn_output, attn_weights, position_bias = self.SelfAttention(
|
| 643 |
+
normed,
|
| 644 |
+
attention_mask_4d=attention_mask_4d,
|
| 645 |
+
position_bias=position_bias,
|
| 646 |
+
output_attentions=output_attentions,
|
| 647 |
+
effective_backend=effective_backend,
|
| 648 |
+
)
|
| 649 |
+
hidden_states = hidden_states + self.dropout(attn_output)
|
| 650 |
+
return hidden_states, attn_weights, position_bias
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class AnkhFFLayer(nn.Module):
|
| 654 |
+
"""Wraps AnkhGatedFFN + layer_norm to match T5Block.layer[1] key naming."""
|
| 655 |
+
|
| 656 |
+
def __init__(self, config: FastAnkhConfig):
|
| 657 |
+
super().__init__()
|
| 658 |
+
self.DenseReluDense = AnkhGatedFFN(config)
|
| 659 |
+
self.layer_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 660 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 661 |
+
|
| 662 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 663 |
+
normed = self.layer_norm(hidden_states)
|
| 664 |
+
hidden_states = hidden_states + self.dropout(self.DenseReluDense(normed))
|
| 665 |
+
return hidden_states
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
class AnkhBlock(nn.Module):
|
| 669 |
+
"""Single transformer block with T5-compatible .layer ModuleList naming."""
|
| 670 |
+
|
| 671 |
+
def __init__(self, config: FastAnkhConfig, has_relative_attention_bias: bool = False):
|
| 672 |
+
super().__init__()
|
| 673 |
+
self.layer = nn.ModuleList(
|
| 674 |
+
[
|
| 675 |
+
AnkhSelfAttentionLayer(config, has_relative_attention_bias),
|
| 676 |
+
AnkhFFLayer(config),
|
| 677 |
+
]
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
def forward(
|
| 681 |
+
self,
|
| 682 |
+
hidden_states: torch.Tensor,
|
| 683 |
+
attention_mask_4d: torch.Tensor | None = None,
|
| 684 |
+
position_bias: torch.Tensor | None = None,
|
| 685 |
+
output_attentions: bool = False,
|
| 686 |
+
effective_backend: AttentionBackend | None = None,
|
| 687 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 688 |
+
hidden_states, attn_weights, position_bias = self.layer[0](
|
| 689 |
+
hidden_states,
|
| 690 |
+
attention_mask_4d=attention_mask_4d,
|
| 691 |
+
position_bias=position_bias,
|
| 692 |
+
output_attentions=output_attentions,
|
| 693 |
+
effective_backend=effective_backend,
|
| 694 |
+
)
|
| 695 |
+
hidden_states = self.layer[1](hidden_states)
|
| 696 |
+
return hidden_states, attn_weights, position_bias
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ---------------------------------------------------------------------------
|
| 700 |
+
# PreTrainedModel base
|
| 701 |
+
# ---------------------------------------------------------------------------
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class AnkhPreTrainedModel(
|
| 705 |
+
_AnkhTokenizerLoadMixin,
|
| 706 |
+
FastPLMsAttentionMixin,
|
| 707 |
+
PreTrainedModel,
|
| 708 |
+
):
|
| 709 |
+
config_class = FastAnkhConfig
|
| 710 |
+
base_model_prefix = "encoder"
|
| 711 |
+
supports_gradient_checkpointing = True
|
| 712 |
+
_no_split_modules: ClassVar[list[str]] = ["AnkhBlock"]
|
| 713 |
+
_supports_flash_attn_2 = False
|
| 714 |
+
_supports_flash_attn_3 = False
|
| 715 |
+
_supports_flex_attn = False
|
| 716 |
+
_fastplms_attention_implementations = ("eager", "sdpa")
|
| 717 |
+
embedding_unsupported_pooling = ("cls",)
|
| 718 |
+
|
| 719 |
+
def __init__(self, config: FastAnkhConfig, *args, **kwargs) -> None:
|
| 720 |
+
super().__init__(config, *args, **kwargs)
|
| 721 |
+
self.__dict__["_fastplms_tokenizer"] = None
|
| 722 |
+
self.__dict__["_fastplms_tokenizer_load_context"] = {}
|
| 723 |
+
|
| 724 |
+
@torch.no_grad()
|
| 725 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 726 |
+
factor = self.config.initializer_factor
|
| 727 |
+
if isinstance(module, nn.Linear):
|
| 728 |
+
module.weight.data.normal_(mean=0.0, std=factor * (self.config.d_model**-0.5))
|
| 729 |
+
elif isinstance(module, nn.Embedding):
|
| 730 |
+
module.weight.data.normal_(mean=0.0, std=factor * 1.0)
|
| 731 |
+
elif isinstance(module, AnkhRMSNorm):
|
| 732 |
+
module.weight.data.fill_(1.0)
|
| 733 |
+
|
| 734 |
+
def post_init(self) -> None:
|
| 735 |
+
super().post_init()
|
| 736 |
+
|
| 737 |
+
def get_output_embeddings(self):
|
| 738 |
+
return None
|
| 739 |
+
|
| 740 |
+
def _embedding_metadata(self, **context: Any) -> Mapping[str, Any]:
|
| 741 |
+
source = _validate_hidden_state_source(context.get("hidden_state_source", "encoder"))
|
| 742 |
+
if source != "encoder":
|
| 743 |
+
raise ValueError(
|
| 744 |
+
"Decoder hidden states require FastAnkhForConditionalGeneration loaded "
|
| 745 |
+
"through AutoModelForSeq2SeqLM."
|
| 746 |
+
)
|
| 747 |
+
return {
|
| 748 |
+
"architecture": "ANKH-T5",
|
| 749 |
+
"hidden_state_stack": "encoder",
|
| 750 |
+
"layer_order": "embedding-plus-transformer-blocks",
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
@property
|
| 754 |
+
def attn_backend(self) -> str:
|
| 755 |
+
return self.config.attn_backend
|
| 756 |
+
|
| 757 |
+
@attn_backend.setter
|
| 758 |
+
def attn_backend(self, backend: str) -> None:
|
| 759 |
+
if backend not in self._fastplms_attention_implementations:
|
| 760 |
+
raise ValueError(
|
| 761 |
+
f"{type(self).__name__} does not support {backend!r}; expected one of "
|
| 762 |
+
f"{self._fastplms_attention_implementations}."
|
| 763 |
+
)
|
| 764 |
+
self.config.attn_backend = backend
|
| 765 |
+
resolved = resolve_attention_backend(backend)
|
| 766 |
+
for module in self.modules():
|
| 767 |
+
if isinstance(module, FAST_ANKH_ENCODER):
|
| 768 |
+
module.attention_backend = resolved
|
| 769 |
+
elif isinstance(module, AnkhSelfAttention):
|
| 770 |
+
module.attn_backend = resolved
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
# ---------------------------------------------------------------------------
|
| 774 |
+
# FAST_ANKH_ENCODER (mirrors T5Stack key naming)
|
| 775 |
+
# ---------------------------------------------------------------------------
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
class FAST_ANKH_ENCODER(AnkhPreTrainedModel, EmbeddingMixin):
|
| 779 |
+
"""Inner encoder that mirrors T5Stack attribute naming for weight compliance.
|
| 780 |
+
|
| 781 |
+
State dict keys: embed_tokens.*, block.{i}.layer.0.SelfAttention.*,
|
| 782 |
+
block.{i}.layer.1.DenseReluDense.*, final_layer_norm.*.
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 786 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 787 |
+
self.config = config
|
| 788 |
+
|
| 789 |
+
resolved = resolve_attention_backend(config.attn_backend)
|
| 790 |
+
if resolved.is_flash:
|
| 791 |
+
raise ValueError(
|
| 792 |
+
"ANKH does not support FlashAttention because it requires relative position bias."
|
| 793 |
+
)
|
| 794 |
+
self.attention_backend = resolved
|
| 795 |
+
|
| 796 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
|
| 797 |
+
self.block = nn.ModuleList(
|
| 798 |
+
[
|
| 799 |
+
AnkhBlock(config, has_relative_attention_bias=(i == 0))
|
| 800 |
+
for i in range(config.num_layers)
|
| 801 |
+
]
|
| 802 |
+
)
|
| 803 |
+
for blk in self.block:
|
| 804 |
+
blk.layer[0].SelfAttention.attn_backend = self.attention_backend
|
| 805 |
+
|
| 806 |
+
self.final_layer_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 807 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 808 |
+
self.gradient_checkpointing = False
|
| 809 |
+
self.post_init()
|
| 810 |
+
|
| 811 |
+
def get_input_embeddings(self):
|
| 812 |
+
return self.embed_tokens
|
| 813 |
+
|
| 814 |
+
def set_input_embeddings(self, value):
|
| 815 |
+
self.embed_tokens = value
|
| 816 |
+
|
| 817 |
+
def _embed(
|
| 818 |
+
self,
|
| 819 |
+
input_ids: torch.Tensor,
|
| 820 |
+
attention_mask: torch.Tensor | None = None,
|
| 821 |
+
hidden_state_index: int = -1,
|
| 822 |
+
store_all_hidden_states: bool = False,
|
| 823 |
+
hidden_state_source: str = "encoder",
|
| 824 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 825 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 826 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 827 |
+
) -> torch.Tensor:
|
| 828 |
+
_require_encoder_embedding_source(
|
| 829 |
+
hidden_state_source,
|
| 830 |
+
decoder_inputs=decoder_inputs,
|
| 831 |
+
decoder_input_ids=decoder_input_ids,
|
| 832 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 833 |
+
)
|
| 834 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 835 |
+
output_hidden_states = store_all_hidden_states or hidden_state_index != -1
|
| 836 |
+
encoder_output = self._run_encoder(
|
| 837 |
+
hidden_states,
|
| 838 |
+
attention_mask=attention_mask,
|
| 839 |
+
output_hidden_states=output_hidden_states,
|
| 840 |
+
)
|
| 841 |
+
return select_hidden_state_embeddings(
|
| 842 |
+
encoder_output.last_hidden_state,
|
| 843 |
+
encoder_output.hidden_states,
|
| 844 |
+
hidden_state_index=hidden_state_index,
|
| 845 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
def _run_encoder(
|
| 849 |
+
self,
|
| 850 |
+
hidden_states: torch.Tensor,
|
| 851 |
+
attention_mask: torch.Tensor | None = None,
|
| 852 |
+
output_hidden_states: bool = False,
|
| 853 |
+
output_attentions: bool = False,
|
| 854 |
+
) -> AnkhEncoderOutput:
|
| 855 |
+
# T5Stack applies this module both to the input embeddings and after
|
| 856 |
+
# final normalization. Keeping those as separate calls preserves the
|
| 857 |
+
# official training-time stochastic path without affecting eval mode.
|
| 858 |
+
hidden_states = self.dropout(hidden_states)
|
| 859 |
+
all_hidden_states = () if output_hidden_states else None
|
| 860 |
+
all_attentions = () if output_attentions else None
|
| 861 |
+
|
| 862 |
+
batch_size, seq_len = hidden_states.shape[:2]
|
| 863 |
+
effective_backend = resolve_attention_backend_for_call(
|
| 864 |
+
self.attention_backend,
|
| 865 |
+
output_attentions=output_attentions,
|
| 866 |
+
)
|
| 867 |
+
_, attention_mask_4d, _ = get_attention_mask(
|
| 868 |
+
effective_backend=effective_backend,
|
| 869 |
+
batch_size=batch_size,
|
| 870 |
+
seq_len=seq_len,
|
| 871 |
+
device=hidden_states.device,
|
| 872 |
+
attention_mask=attention_mask,
|
| 873 |
+
dtype=hidden_states.dtype,
|
| 874 |
+
mask_semantics="padding",
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
position_bias = None
|
| 878 |
+
|
| 879 |
+
for layer_module in self.block:
|
| 880 |
+
if output_hidden_states:
|
| 881 |
+
all_hidden_states = (*all_hidden_states, hidden_states)
|
| 882 |
+
|
| 883 |
+
if self.gradient_checkpointing and self.training:
|
| 884 |
+
hidden_states, attn_weights, position_bias = self._gradient_checkpointing_func(
|
| 885 |
+
layer_module.__call__,
|
| 886 |
+
hidden_states,
|
| 887 |
+
attention_mask_4d,
|
| 888 |
+
position_bias,
|
| 889 |
+
output_attentions,
|
| 890 |
+
effective_backend,
|
| 891 |
+
)
|
| 892 |
+
else:
|
| 893 |
+
hidden_states, attn_weights, position_bias = layer_module(
|
| 894 |
+
hidden_states,
|
| 895 |
+
attention_mask_4d=attention_mask_4d,
|
| 896 |
+
position_bias=position_bias,
|
| 897 |
+
output_attentions=output_attentions,
|
| 898 |
+
effective_backend=effective_backend,
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
if all_attentions is not None:
|
| 902 |
+
all_attentions = (*all_attentions, attn_weights)
|
| 903 |
+
|
| 904 |
+
hidden_states = self.dropout(self.final_layer_norm(hidden_states))
|
| 905 |
+
|
| 906 |
+
if output_hidden_states:
|
| 907 |
+
all_hidden_states = (*all_hidden_states, hidden_states)
|
| 908 |
+
|
| 909 |
+
return AnkhEncoderOutput(
|
| 910 |
+
last_hidden_state=hidden_states,
|
| 911 |
+
hidden_states=all_hidden_states,
|
| 912 |
+
attentions=all_attentions,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
def forward(
|
| 916 |
+
self,
|
| 917 |
+
input_ids: torch.Tensor | None = None,
|
| 918 |
+
attention_mask: torch.Tensor | None = None,
|
| 919 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 920 |
+
output_hidden_states: bool | None = None,
|
| 921 |
+
output_attentions: bool | None = None,
|
| 922 |
+
return_dict: bool | None = None,
|
| 923 |
+
) -> AnkhEncoderOutput | tuple[torch.Tensor, ...]:
|
| 924 |
+
output_attentions = (
|
| 925 |
+
output_attentions if output_attentions is not None else self.config.output_attentions
|
| 926 |
+
)
|
| 927 |
+
output_hidden_states = (
|
| 928 |
+
output_hidden_states
|
| 929 |
+
if output_hidden_states is not None
|
| 930 |
+
else self.config.output_hidden_states
|
| 931 |
+
)
|
| 932 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 933 |
+
|
| 934 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 935 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 936 |
+
elif input_ids is not None:
|
| 937 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 938 |
+
elif inputs_embeds is not None:
|
| 939 |
+
hidden_states = inputs_embeds
|
| 940 |
+
else:
|
| 941 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 942 |
+
|
| 943 |
+
outputs = self._run_encoder(
|
| 944 |
+
hidden_states,
|
| 945 |
+
attention_mask=attention_mask,
|
| 946 |
+
output_hidden_states=output_hidden_states or False,
|
| 947 |
+
output_attentions=output_attentions or False,
|
| 948 |
+
)
|
| 949 |
+
return outputs if return_dict else outputs.to_tuple()
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
# ---------------------------------------------------------------------------
|
| 953 |
+
# Model classes
|
| 954 |
+
# ---------------------------------------------------------------------------
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
class FastAnkhModel(AnkhPreTrainedModel, EmbeddingMixin):
|
| 958 |
+
"""ANKH encoder model for embedding extraction."""
|
| 959 |
+
|
| 960 |
+
_tied_weights_keys: ClassVar[dict[str, str]] = {"encoder.embed_tokens.weight": "shared.weight"}
|
| 961 |
+
# The published ANKH checkpoint is the complete official T5 state. AutoModel
|
| 962 |
+
# intentionally exposes only its encoder view without allocating a decoder.
|
| 963 |
+
_keys_to_ignore_on_load_unexpected: ClassVar[list[str]] = [
|
| 964 |
+
r"^decoder\.",
|
| 965 |
+
r"^lm_head\.",
|
| 966 |
+
]
|
| 967 |
+
|
| 968 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 969 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 970 |
+
self.config = config
|
| 971 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 972 |
+
self.encoder = FAST_ANKH_ENCODER(config)
|
| 973 |
+
self.encoder.embed_tokens = self.shared
|
| 974 |
+
self.post_init()
|
| 975 |
+
|
| 976 |
+
def get_input_embeddings(self):
|
| 977 |
+
return self.encoder.embed_tokens
|
| 978 |
+
|
| 979 |
+
def set_input_embeddings(self, value):
|
| 980 |
+
self.shared = value
|
| 981 |
+
self.encoder.embed_tokens = value
|
| 982 |
+
|
| 983 |
+
def _embed(
|
| 984 |
+
self,
|
| 985 |
+
input_ids: torch.Tensor,
|
| 986 |
+
attention_mask: torch.Tensor | None = None,
|
| 987 |
+
hidden_state_index: int = -1,
|
| 988 |
+
store_all_hidden_states: bool = False,
|
| 989 |
+
**embedding_kwargs,
|
| 990 |
+
) -> torch.Tensor:
|
| 991 |
+
return self.encoder._embed(
|
| 992 |
+
input_ids,
|
| 993 |
+
attention_mask,
|
| 994 |
+
hidden_state_index=hidden_state_index,
|
| 995 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 996 |
+
**embedding_kwargs,
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
+
def forward(
|
| 1000 |
+
self,
|
| 1001 |
+
input_ids: torch.Tensor | None = None,
|
| 1002 |
+
attention_mask: torch.Tensor | None = None,
|
| 1003 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1004 |
+
output_hidden_states: bool | None = None,
|
| 1005 |
+
output_attentions: bool | None = None,
|
| 1006 |
+
return_dict: bool | None = None,
|
| 1007 |
+
) -> AnkhEncoderOutput | tuple[torch.Tensor, ...]:
|
| 1008 |
+
return self.encoder(
|
| 1009 |
+
input_ids=input_ids,
|
| 1010 |
+
attention_mask=attention_mask,
|
| 1011 |
+
inputs_embeds=inputs_embeds,
|
| 1012 |
+
output_hidden_states=output_hidden_states,
|
| 1013 |
+
output_attentions=output_attentions,
|
| 1014 |
+
return_dict=return_dict,
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
class FastAnkhForMaskedLMExtension(
|
| 1019 |
+
FastPLMTestTimeTrainingMixin, AnkhPreTrainedModel, EmbeddingMixin
|
| 1020 |
+
):
|
| 1021 |
+
"""ANKH encoder with LM head for masked language modeling.
|
| 1022 |
+
|
| 1023 |
+
NOTE: The LM head is initialized from the shared embedding weights but is NOT
|
| 1024 |
+
tied. The original ANKH models were trained with T5's span corruption objective
|
| 1025 |
+
using an encoder-decoder architecture. This encoder-only MaskedLM variant is
|
| 1026 |
+
not pre-trained for standard MLM and requires additional fine-tuning.
|
| 1027 |
+
"""
|
| 1028 |
+
|
| 1029 |
+
_tied_weights_keys: ClassVar[dict[str, str]] = {"encoder.embed_tokens.weight": "shared.weight"}
|
| 1030 |
+
_keys_to_ignore_on_load_unexpected: ClassVar[list[str]] = [r"^decoder\."]
|
| 1031 |
+
|
| 1032 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 1033 |
+
# The historical Synthyra extension stores an independent output head.
|
| 1034 |
+
config.tie_word_embeddings = False
|
| 1035 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 1036 |
+
self.config = config
|
| 1037 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1038 |
+
self.encoder = FAST_ANKH_ENCODER(config)
|
| 1039 |
+
self.encoder.embed_tokens = self.shared
|
| 1040 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 1041 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
| 1042 |
+
self.post_init()
|
| 1043 |
+
self.init_ttt({"lora_target_replace_module": "AnkhSelfAttention"})
|
| 1044 |
+
|
| 1045 |
+
def get_input_embeddings(self):
|
| 1046 |
+
return self.encoder.embed_tokens
|
| 1047 |
+
|
| 1048 |
+
def set_input_embeddings(self, value):
|
| 1049 |
+
self.shared = value
|
| 1050 |
+
self.encoder.embed_tokens = value
|
| 1051 |
+
|
| 1052 |
+
def get_output_embeddings(self):
|
| 1053 |
+
return self.lm_head
|
| 1054 |
+
|
| 1055 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1056 |
+
self.lm_head = new_embeddings
|
| 1057 |
+
|
| 1058 |
+
def _embed(
|
| 1059 |
+
self,
|
| 1060 |
+
input_ids: torch.Tensor,
|
| 1061 |
+
attention_mask: torch.Tensor | None = None,
|
| 1062 |
+
hidden_state_index: int = -1,
|
| 1063 |
+
store_all_hidden_states: bool = False,
|
| 1064 |
+
**embedding_kwargs,
|
| 1065 |
+
) -> torch.Tensor:
|
| 1066 |
+
return self.encoder._embed(
|
| 1067 |
+
input_ids,
|
| 1068 |
+
attention_mask,
|
| 1069 |
+
hidden_state_index=hidden_state_index,
|
| 1070 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1071 |
+
**embedding_kwargs,
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
def _ttt_get_trainable_modules(self) -> list[nn.Module]:
|
| 1075 |
+
return [self.encoder]
|
| 1076 |
+
|
| 1077 |
+
def _ttt_tokenize(
|
| 1078 |
+
self,
|
| 1079 |
+
seq: str | list[str] | None = None,
|
| 1080 |
+
input_ids: torch.Tensor | None = None,
|
| 1081 |
+
**kwargs,
|
| 1082 |
+
) -> torch.Tensor:
|
| 1083 |
+
del kwargs
|
| 1084 |
+
if input_ids is not None:
|
| 1085 |
+
return input_ids
|
| 1086 |
+
if seq is None:
|
| 1087 |
+
raise ValueError("Pass either seq or input_ids for ANKH TTT.")
|
| 1088 |
+
sequences = [seq] if isinstance(seq, str) else seq
|
| 1089 |
+
tokenized = tokenize_ankh_sequences(
|
| 1090 |
+
self.tokenizer,
|
| 1091 |
+
sequences,
|
| 1092 |
+
return_tensors="pt",
|
| 1093 |
+
padding=True,
|
| 1094 |
+
)
|
| 1095 |
+
return tokenized["input_ids"]
|
| 1096 |
+
|
| 1097 |
+
def _ttt_replacement_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 1098 |
+
amino_acids = "ACDEFGHIKLMNPQRSTVWY"
|
| 1099 |
+
ids = [self.tokenizer.convert_tokens_to_ids(aa) for aa in amino_acids]
|
| 1100 |
+
return torch.tensor(ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 1101 |
+
|
| 1102 |
+
def forward(
|
| 1103 |
+
self,
|
| 1104 |
+
input_ids: torch.Tensor | None = None,
|
| 1105 |
+
attention_mask: torch.Tensor | None = None,
|
| 1106 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1107 |
+
labels: torch.Tensor | None = None,
|
| 1108 |
+
output_hidden_states: bool | None = None,
|
| 1109 |
+
output_attentions: bool | None = None,
|
| 1110 |
+
return_dict: bool | None = None,
|
| 1111 |
+
) -> MaskedLMOutput | tuple[torch.Tensor, ...]:
|
| 1112 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1113 |
+
outputs = self.encoder(
|
| 1114 |
+
input_ids=input_ids,
|
| 1115 |
+
attention_mask=attention_mask,
|
| 1116 |
+
inputs_embeds=inputs_embeds,
|
| 1117 |
+
output_hidden_states=output_hidden_states,
|
| 1118 |
+
output_attentions=output_attentions,
|
| 1119 |
+
return_dict=True,
|
| 1120 |
+
)
|
| 1121 |
+
sequence_output = outputs.last_hidden_state
|
| 1122 |
+
logits = self.lm_head(sequence_output)
|
| 1123 |
+
|
| 1124 |
+
loss = None
|
| 1125 |
+
if labels is not None:
|
| 1126 |
+
labels = labels.to(logits.device)
|
| 1127 |
+
loss = self.loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1128 |
+
|
| 1129 |
+
if not return_dict:
|
| 1130 |
+
output = (logits, *outputs.to_tuple()[1:])
|
| 1131 |
+
return (loss, *output) if loss is not None else output
|
| 1132 |
+
|
| 1133 |
+
return MaskedLMOutput(
|
| 1134 |
+
loss=loss,
|
| 1135 |
+
logits=logits,
|
| 1136 |
+
hidden_states=outputs.hidden_states,
|
| 1137 |
+
attentions=outputs.attentions,
|
| 1138 |
+
)
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
class FastAnkhForConditionalGeneration(
|
| 1142 |
+
_AnkhTokenizerLoadMixin,
|
| 1143 |
+
T5ForConditionalGeneration,
|
| 1144 |
+
EmbeddingMixin,
|
| 1145 |
+
):
|
| 1146 |
+
"""Official ANKH sequence-to-sequence architecture with exact T5 state keys.
|
| 1147 |
+
|
| 1148 |
+
ANKH generation checkpoints are ordinary T5 conditional-generation models.
|
| 1149 |
+
This class intentionally delegates their decoder, cross-attention, language
|
| 1150 |
+
model head, caching, generation, and tied-weight behavior to Transformers.
|
| 1151 |
+
The optimized encoder-only implementation remains available through
|
| 1152 |
+
:class:`FastAnkhModel`.
|
| 1153 |
+
"""
|
| 1154 |
+
|
| 1155 |
+
config_class = FastAnkhConfig
|
| 1156 |
+
embedding_unsupported_pooling = ("cls",)
|
| 1157 |
+
_fastplms_attention_implementations = ("eager",)
|
| 1158 |
+
|
| 1159 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 1160 |
+
requested_backend = getattr(config, "_attn_implementation", None) or config.attn_backend
|
| 1161 |
+
if requested_backend not in (None, "eager"):
|
| 1162 |
+
raise ValueError(
|
| 1163 |
+
"ANKH sequence-to-sequence checkpoints support only eager attention; "
|
| 1164 |
+
f"received {requested_backend!r}. Use FastAnkhModel for optimized "
|
| 1165 |
+
"encoder embeddings."
|
| 1166 |
+
)
|
| 1167 |
+
set_config_attn_implementation(config, "eager")
|
| 1168 |
+
super().__init__(config, **kwargs)
|
| 1169 |
+
self.__dict__["_fastplms_tokenizer"] = None
|
| 1170 |
+
self.__dict__["_fastplms_tokenizer_load_context"] = {}
|
| 1171 |
+
|
| 1172 |
+
def forward(
|
| 1173 |
+
self,
|
| 1174 |
+
input_ids: torch.Tensor | None = None,
|
| 1175 |
+
attention_mask: torch.Tensor | None = None,
|
| 1176 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1177 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1178 |
+
encoder_outputs: Any | None = None,
|
| 1179 |
+
past_key_values: Any | None = None,
|
| 1180 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1181 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 1182 |
+
labels: torch.Tensor | None = None,
|
| 1183 |
+
use_cache: bool | None = None,
|
| 1184 |
+
output_attentions: bool | None = None,
|
| 1185 |
+
output_hidden_states: bool | None = None,
|
| 1186 |
+
return_dict: bool | None = None,
|
| 1187 |
+
) -> Any:
|
| 1188 |
+
"""Run official T5 seq2seq behavior with a fail-closed public signature.
|
| 1189 |
+
|
| 1190 |
+
Transformers' T5 forward currently accepts and silently ignores arbitrary
|
| 1191 |
+
keyword arguments. FastPLMs keeps the supported T5 arguments explicit so a
|
| 1192 |
+
misspelled generation, cache, or conditioning argument cannot appear to
|
| 1193 |
+
have taken effect.
|
| 1194 |
+
"""
|
| 1195 |
+
|
| 1196 |
+
return super().forward(
|
| 1197 |
+
input_ids=input_ids,
|
| 1198 |
+
attention_mask=attention_mask,
|
| 1199 |
+
decoder_input_ids=decoder_input_ids,
|
| 1200 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1201 |
+
encoder_outputs=encoder_outputs,
|
| 1202 |
+
past_key_values=past_key_values,
|
| 1203 |
+
inputs_embeds=inputs_embeds,
|
| 1204 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1205 |
+
labels=labels,
|
| 1206 |
+
use_cache=use_cache,
|
| 1207 |
+
output_attentions=output_attentions,
|
| 1208 |
+
output_hidden_states=output_hidden_states,
|
| 1209 |
+
return_dict=return_dict,
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
def _prepare_decoder_embedding_inputs(
|
| 1213 |
+
self,
|
| 1214 |
+
*,
|
| 1215 |
+
batch_size: int,
|
| 1216 |
+
decoder_inputs: Sequence[str] | None,
|
| 1217 |
+
decoder_input_ids: torch.Tensor | None,
|
| 1218 |
+
decoder_attention_mask: torch.Tensor | None,
|
| 1219 |
+
tokenizer: Any | None = None,
|
| 1220 |
+
) -> tuple[torch.Tensor, torch.Tensor, Any]:
|
| 1221 |
+
if (decoder_inputs is None) == (decoder_input_ids is None):
|
| 1222 |
+
raise ValueError(
|
| 1223 |
+
"hidden_state_source='decoder' requires exactly one of "
|
| 1224 |
+
"decoder_inputs or decoder_input_ids. Decoder inputs are task-specific "
|
| 1225 |
+
"and FastPLMs will not synthesize shifted encoder tokens."
|
| 1226 |
+
)
|
| 1227 |
+
resolved_tokenizer = configure_ankh_tokenizer(
|
| 1228 |
+
tokenizer if tokenizer is not None else self.tokenizer
|
| 1229 |
+
)
|
| 1230 |
+
if decoder_inputs is not None:
|
| 1231 |
+
if decoder_attention_mask is not None:
|
| 1232 |
+
raise ValueError(
|
| 1233 |
+
"decoder_attention_mask may only accompany decoder_input_ids; "
|
| 1234 |
+
"decoder_inputs are tokenized with their own attention mask."
|
| 1235 |
+
)
|
| 1236 |
+
values = [decoder_inputs] if isinstance(decoder_inputs, str) else list(decoder_inputs)
|
| 1237 |
+
if len(values) != batch_size:
|
| 1238 |
+
raise ValueError(
|
| 1239 |
+
"decoder_inputs must align one-to-one with encoder inputs; "
|
| 1240 |
+
f"expected {batch_size}, received {len(values)}."
|
| 1241 |
+
)
|
| 1242 |
+
encoded = tokenize_ankh_decoder_prompts(
|
| 1243 |
+
resolved_tokenizer,
|
| 1244 |
+
values,
|
| 1245 |
+
return_tensors="pt",
|
| 1246 |
+
padding=True,
|
| 1247 |
+
truncation=False,
|
| 1248 |
+
)
|
| 1249 |
+
decoder_input_ids = encoded["input_ids"]
|
| 1250 |
+
decoder_attention_mask = encoded.get("attention_mask")
|
| 1251 |
+
if decoder_input_ids is None:
|
| 1252 |
+
raise RuntimeError(
|
| 1253 |
+
"Decoder input resolution completed without decoder_input_ids."
|
| 1254 |
+
)
|
| 1255 |
+
if decoder_input_ids.ndim != 2 or decoder_input_ids.shape[0] != batch_size:
|
| 1256 |
+
raise ValueError(
|
| 1257 |
+
"decoder_input_ids must have shape (batch, decoder_sequence_length); "
|
| 1258 |
+
f"expected batch {batch_size}, received {tuple(decoder_input_ids.shape)}."
|
| 1259 |
+
)
|
| 1260 |
+
if decoder_attention_mask is None:
|
| 1261 |
+
pad_token_id = self.config.pad_token_id
|
| 1262 |
+
decoder_attention_mask = (
|
| 1263 |
+
torch.ones_like(decoder_input_ids, dtype=torch.bool)
|
| 1264 |
+
if pad_token_id is None
|
| 1265 |
+
else decoder_input_ids.ne(pad_token_id)
|
| 1266 |
+
)
|
| 1267 |
+
decoder_start_token_id = self.config.decoder_start_token_id
|
| 1268 |
+
if (
|
| 1269 |
+
decoder_input_ids.shape[1] > 0
|
| 1270 |
+
and decoder_start_token_id is not None
|
| 1271 |
+
and decoder_start_token_id == pad_token_id
|
| 1272 |
+
):
|
| 1273 |
+
decoder_attention_mask[:, 0] |= decoder_input_ids[:, 0].eq(decoder_start_token_id)
|
| 1274 |
+
if tuple(decoder_attention_mask.shape) != tuple(decoder_input_ids.shape):
|
| 1275 |
+
raise ValueError(
|
| 1276 |
+
"decoder_attention_mask must have the same shape as decoder_input_ids; "
|
| 1277 |
+
f"received {tuple(decoder_attention_mask.shape)} and "
|
| 1278 |
+
f"{tuple(decoder_input_ids.shape)}."
|
| 1279 |
+
)
|
| 1280 |
+
device = self.shared.weight.device
|
| 1281 |
+
return (
|
| 1282 |
+
decoder_input_ids.to(device=device),
|
| 1283 |
+
decoder_attention_mask.to(device=device),
|
| 1284 |
+
resolved_tokenizer,
|
| 1285 |
+
)
|
| 1286 |
+
|
| 1287 |
+
def _extract_embedding_stack(
|
| 1288 |
+
self,
|
| 1289 |
+
input_ids: torch.Tensor,
|
| 1290 |
+
attention_mask: torch.Tensor | None,
|
| 1291 |
+
*,
|
| 1292 |
+
hidden_state_source: str,
|
| 1293 |
+
hidden_state_index: int,
|
| 1294 |
+
store_all_hidden_states: bool,
|
| 1295 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 1296 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1297 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1298 |
+
tokenizer: Any | None = None,
|
| 1299 |
+
output_attentions: bool = False,
|
| 1300 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor, ...] | None]:
|
| 1301 |
+
source = _validate_hidden_state_source(hidden_state_source)
|
| 1302 |
+
device = self.shared.weight.device
|
| 1303 |
+
input_ids = input_ids.to(device=device)
|
| 1304 |
+
if attention_mask is None:
|
| 1305 |
+
attention_mask = input_ids.ne(self.config.pad_token_id)
|
| 1306 |
+
attention_mask = attention_mask.to(device=device)
|
| 1307 |
+
need_hidden_states = store_all_hidden_states or hidden_state_index != -1
|
| 1308 |
+
encoder_outputs = self.encoder(
|
| 1309 |
+
input_ids=input_ids,
|
| 1310 |
+
attention_mask=attention_mask,
|
| 1311 |
+
output_hidden_states=need_hidden_states,
|
| 1312 |
+
output_attentions=output_attentions and source == "encoder",
|
| 1313 |
+
return_dict=True,
|
| 1314 |
+
)
|
| 1315 |
+
if source == "encoder":
|
| 1316 |
+
if any(
|
| 1317 |
+
value is not None
|
| 1318 |
+
for value in (decoder_inputs, decoder_input_ids, decoder_attention_mask)
|
| 1319 |
+
):
|
| 1320 |
+
raise ValueError(
|
| 1321 |
+
"Decoder inputs are only valid when hidden_state_source='decoder'."
|
| 1322 |
+
)
|
| 1323 |
+
X = select_hidden_state_embeddings(
|
| 1324 |
+
encoder_outputs.last_hidden_state,
|
| 1325 |
+
encoder_outputs.hidden_states,
|
| 1326 |
+
hidden_state_index=hidden_state_index,
|
| 1327 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1328 |
+
)
|
| 1329 |
+
return X, input_ids, attention_mask, encoder_outputs.attentions
|
| 1330 |
+
|
| 1331 |
+
decoder_input_ids, decoder_attention_mask, _ = self._prepare_decoder_embedding_inputs(
|
| 1332 |
+
batch_size=input_ids.shape[0],
|
| 1333 |
+
decoder_inputs=decoder_inputs,
|
| 1334 |
+
decoder_input_ids=decoder_input_ids,
|
| 1335 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1336 |
+
tokenizer=tokenizer,
|
| 1337 |
+
)
|
| 1338 |
+
decoder_outputs = self.decoder(
|
| 1339 |
+
input_ids=decoder_input_ids,
|
| 1340 |
+
attention_mask=decoder_attention_mask,
|
| 1341 |
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
| 1342 |
+
encoder_attention_mask=attention_mask,
|
| 1343 |
+
use_cache=False,
|
| 1344 |
+
output_hidden_states=need_hidden_states,
|
| 1345 |
+
output_attentions=output_attentions,
|
| 1346 |
+
return_dict=True,
|
| 1347 |
+
)
|
| 1348 |
+
X = select_hidden_state_embeddings(
|
| 1349 |
+
decoder_outputs.last_hidden_state,
|
| 1350 |
+
decoder_outputs.hidden_states,
|
| 1351 |
+
hidden_state_index=hidden_state_index,
|
| 1352 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1353 |
+
)
|
| 1354 |
+
return X, decoder_input_ids, decoder_attention_mask, decoder_outputs.attentions
|
| 1355 |
+
|
| 1356 |
+
def _embed(
|
| 1357 |
+
self,
|
| 1358 |
+
input_ids: torch.Tensor,
|
| 1359 |
+
attention_mask: torch.Tensor | None = None,
|
| 1360 |
+
hidden_state_index: int = -1,
|
| 1361 |
+
store_all_hidden_states: bool = False,
|
| 1362 |
+
hidden_state_source: str = "encoder",
|
| 1363 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 1364 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1365 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1366 |
+
tokenizer: Any | None = None,
|
| 1367 |
+
) -> torch.Tensor:
|
| 1368 |
+
X, _, _, _ = self._extract_embedding_stack(
|
| 1369 |
+
input_ids,
|
| 1370 |
+
attention_mask,
|
| 1371 |
+
hidden_state_source=hidden_state_source,
|
| 1372 |
+
hidden_state_index=hidden_state_index,
|
| 1373 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1374 |
+
decoder_inputs=decoder_inputs,
|
| 1375 |
+
decoder_input_ids=decoder_input_ids,
|
| 1376 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1377 |
+
tokenizer=tokenizer,
|
| 1378 |
+
)
|
| 1379 |
+
return X
|
| 1380 |
+
|
| 1381 |
+
def _embedding_batch(
|
| 1382 |
+
self,
|
| 1383 |
+
sequences: Sequence[str],
|
| 1384 |
+
*,
|
| 1385 |
+
tokenizer: Any | None = None,
|
| 1386 |
+
max_length: int | None = None,
|
| 1387 |
+
truncate: bool = True,
|
| 1388 |
+
need_attentions: bool = False,
|
| 1389 |
+
hidden_state_source: str = "encoder",
|
| 1390 |
+
hidden_state_index: int = -1,
|
| 1391 |
+
store_all_hidden_states: bool = False,
|
| 1392 |
+
decoder_inputs: Sequence[str] | None = None,
|
| 1393 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1394 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1395 |
+
) -> EmbeddingBatch:
|
| 1396 |
+
del max_length, truncate # The shared runner already crops biological residues.
|
| 1397 |
+
resolved_tokenizer = configure_ankh_tokenizer(
|
| 1398 |
+
tokenizer if tokenizer is not None else self.tokenizer
|
| 1399 |
+
)
|
| 1400 |
+
encoded = tokenize_ankh_sequences(
|
| 1401 |
+
resolved_tokenizer,
|
| 1402 |
+
list(sequences),
|
| 1403 |
+
return_tensors="pt",
|
| 1404 |
+
padding=True,
|
| 1405 |
+
truncation=False,
|
| 1406 |
+
)
|
| 1407 |
+
device = self.shared.weight.device
|
| 1408 |
+
input_ids = encoded["input_ids"].to(device=device)
|
| 1409 |
+
attention_mask = encoded.get("attention_mask", input_ids.new_ones(input_ids.shape)).to(
|
| 1410 |
+
device=device
|
| 1411 |
+
)
|
| 1412 |
+
X, selected_ids, selected_attention_mask, attentions = self._extract_embedding_stack(
|
| 1413 |
+
input_ids,
|
| 1414 |
+
attention_mask,
|
| 1415 |
+
hidden_state_source=hidden_state_source,
|
| 1416 |
+
hidden_state_index=hidden_state_index,
|
| 1417 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1418 |
+
decoder_inputs=decoder_inputs,
|
| 1419 |
+
decoder_input_ids=decoder_input_ids,
|
| 1420 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1421 |
+
tokenizer=resolved_tokenizer,
|
| 1422 |
+
output_attentions=need_attentions,
|
| 1423 |
+
)
|
| 1424 |
+
residue_mask = _biological_token_mask(
|
| 1425 |
+
selected_ids,
|
| 1426 |
+
selected_attention_mask,
|
| 1427 |
+
resolved_tokenizer,
|
| 1428 |
+
)
|
| 1429 |
+
return EmbeddingBatch(X=X, residue_mask=residue_mask, attentions=attentions)
|
| 1430 |
+
|
| 1431 |
+
def _embedding_metadata(self, **context: Any) -> Mapping[str, Any]:
|
| 1432 |
+
source = _validate_hidden_state_source(context.get("hidden_state_source", "encoder"))
|
| 1433 |
+
return {
|
| 1434 |
+
"architecture": "ANKH-T5",
|
| 1435 |
+
"hidden_state_stack": source,
|
| 1436 |
+
"layer_order": "embedding-plus-transformer-blocks",
|
| 1437 |
+
"decoder_inputs": "explicit-task-inputs-required" if source == "decoder" else None,
|
| 1438 |
+
"decoder_residue_mask": (
|
| 1439 |
+
"attention-mask-minus-tokenizer-specials" if source == "decoder" else None
|
| 1440 |
+
),
|
| 1441 |
+
}
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
class FastAnkhForSequenceClassification(AnkhPreTrainedModel, EmbeddingMixin):
|
| 1445 |
+
_tied_weights_keys: ClassVar[dict[str, str]] = {"encoder.embed_tokens.weight": "shared.weight"}
|
| 1446 |
+
_keys_to_ignore_on_load_unexpected: ClassVar[list[str]] = [
|
| 1447 |
+
r"^decoder\.",
|
| 1448 |
+
r"^lm_head\.",
|
| 1449 |
+
]
|
| 1450 |
+
|
| 1451 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 1452 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 1453 |
+
self.num_labels = config.num_labels
|
| 1454 |
+
self.config = config
|
| 1455 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1456 |
+
self.encoder = FAST_ANKH_ENCODER(config)
|
| 1457 |
+
self.encoder.embed_tokens = self.shared
|
| 1458 |
+
self.classifier = nn.Linear(config.d_model, config.num_labels)
|
| 1459 |
+
self.mse = nn.MSELoss()
|
| 1460 |
+
self.ce = nn.CrossEntropyLoss()
|
| 1461 |
+
self.bce = nn.BCEWithLogitsLoss()
|
| 1462 |
+
self.post_init()
|
| 1463 |
+
|
| 1464 |
+
def get_input_embeddings(self):
|
| 1465 |
+
return self.encoder.embed_tokens
|
| 1466 |
+
|
| 1467 |
+
def set_input_embeddings(self, value):
|
| 1468 |
+
self.shared = value
|
| 1469 |
+
self.encoder.embed_tokens = value
|
| 1470 |
+
|
| 1471 |
+
def _embed(
|
| 1472 |
+
self,
|
| 1473 |
+
input_ids: torch.Tensor,
|
| 1474 |
+
attention_mask: torch.Tensor | None = None,
|
| 1475 |
+
hidden_state_index: int = -1,
|
| 1476 |
+
store_all_hidden_states: bool = False,
|
| 1477 |
+
**embedding_kwargs,
|
| 1478 |
+
) -> torch.Tensor:
|
| 1479 |
+
return self.encoder._embed(
|
| 1480 |
+
input_ids,
|
| 1481 |
+
attention_mask,
|
| 1482 |
+
hidden_state_index=hidden_state_index,
|
| 1483 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1484 |
+
**embedding_kwargs,
|
| 1485 |
+
)
|
| 1486 |
+
|
| 1487 |
+
def forward(
|
| 1488 |
+
self,
|
| 1489 |
+
input_ids: torch.Tensor | None = None,
|
| 1490 |
+
attention_mask: torch.Tensor | None = None,
|
| 1491 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1492 |
+
labels: torch.Tensor | None = None,
|
| 1493 |
+
output_hidden_states: bool | None = None,
|
| 1494 |
+
output_attentions: bool | None = None,
|
| 1495 |
+
return_dict: bool | None = None,
|
| 1496 |
+
) -> SequenceClassifierOutput | tuple[torch.Tensor, ...]:
|
| 1497 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1498 |
+
outputs = self.encoder(
|
| 1499 |
+
input_ids=input_ids,
|
| 1500 |
+
attention_mask=attention_mask,
|
| 1501 |
+
inputs_embeds=inputs_embeds,
|
| 1502 |
+
output_hidden_states=output_hidden_states,
|
| 1503 |
+
output_attentions=output_attentions,
|
| 1504 |
+
return_dict=True,
|
| 1505 |
+
)
|
| 1506 |
+
# Pool: mean over non-padding tokens
|
| 1507 |
+
sequence_output = outputs.last_hidden_state
|
| 1508 |
+
if attention_mask is not None:
|
| 1509 |
+
mask = attention_mask.unsqueeze(-1).to(sequence_output.dtype)
|
| 1510 |
+
pooled = (sequence_output * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1)
|
| 1511 |
+
else:
|
| 1512 |
+
pooled = sequence_output.mean(dim=1)
|
| 1513 |
+
logits = self.classifier(pooled)
|
| 1514 |
+
|
| 1515 |
+
loss = None
|
| 1516 |
+
if labels is not None:
|
| 1517 |
+
labels = labels.to(logits.device)
|
| 1518 |
+
if self.config.problem_type is None:
|
| 1519 |
+
if self.num_labels == 1:
|
| 1520 |
+
self.config.problem_type = "regression"
|
| 1521 |
+
elif self.num_labels > 1 and (
|
| 1522 |
+
labels.dtype == torch.long or labels.dtype == torch.int
|
| 1523 |
+
):
|
| 1524 |
+
self.config.problem_type = "single_label_classification"
|
| 1525 |
+
else:
|
| 1526 |
+
self.config.problem_type = "multi_label_classification"
|
| 1527 |
+
|
| 1528 |
+
if self.config.problem_type == "regression":
|
| 1529 |
+
loss = (
|
| 1530 |
+
self.mse(logits.squeeze(), labels.squeeze())
|
| 1531 |
+
if self.num_labels == 1
|
| 1532 |
+
else self.mse(logits, labels)
|
| 1533 |
+
)
|
| 1534 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1535 |
+
loss = self.ce(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1536 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1537 |
+
loss = self.bce(logits, labels)
|
| 1538 |
+
|
| 1539 |
+
if not return_dict:
|
| 1540 |
+
output = (logits, *outputs.to_tuple()[1:])
|
| 1541 |
+
return (loss, *output) if loss is not None else output
|
| 1542 |
+
|
| 1543 |
+
return SequenceClassifierOutput(
|
| 1544 |
+
loss=loss,
|
| 1545 |
+
logits=logits,
|
| 1546 |
+
hidden_states=outputs.hidden_states,
|
| 1547 |
+
attentions=outputs.attentions,
|
| 1548 |
+
)
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
class FastAnkhForTokenClassification(AnkhPreTrainedModel, EmbeddingMixin):
|
| 1552 |
+
_tied_weights_keys: ClassVar[dict[str, str]] = {"encoder.embed_tokens.weight": "shared.weight"}
|
| 1553 |
+
_keys_to_ignore_on_load_unexpected: ClassVar[list[str]] = [
|
| 1554 |
+
r"^decoder\.",
|
| 1555 |
+
r"^lm_head\.",
|
| 1556 |
+
]
|
| 1557 |
+
|
| 1558 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 1559 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 1560 |
+
self.num_labels = config.num_labels
|
| 1561 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
| 1562 |
+
self.encoder = FAST_ANKH_ENCODER(config)
|
| 1563 |
+
self.encoder.embed_tokens = self.shared
|
| 1564 |
+
self.classifier = nn.Linear(config.d_model, config.num_labels)
|
| 1565 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
| 1566 |
+
self.post_init()
|
| 1567 |
+
|
| 1568 |
+
def get_input_embeddings(self):
|
| 1569 |
+
return self.encoder.embed_tokens
|
| 1570 |
+
|
| 1571 |
+
def set_input_embeddings(self, value):
|
| 1572 |
+
self.shared = value
|
| 1573 |
+
self.encoder.embed_tokens = value
|
| 1574 |
+
|
| 1575 |
+
def _embed(
|
| 1576 |
+
self,
|
| 1577 |
+
input_ids: torch.Tensor,
|
| 1578 |
+
attention_mask: torch.Tensor | None = None,
|
| 1579 |
+
hidden_state_index: int = -1,
|
| 1580 |
+
store_all_hidden_states: bool = False,
|
| 1581 |
+
**embedding_kwargs,
|
| 1582 |
+
) -> torch.Tensor:
|
| 1583 |
+
return self.encoder._embed(
|
| 1584 |
+
input_ids,
|
| 1585 |
+
attention_mask,
|
| 1586 |
+
hidden_state_index=hidden_state_index,
|
| 1587 |
+
store_all_hidden_states=store_all_hidden_states,
|
| 1588 |
+
**embedding_kwargs,
|
| 1589 |
+
)
|
| 1590 |
+
|
| 1591 |
+
def forward(
|
| 1592 |
+
self,
|
| 1593 |
+
input_ids: torch.Tensor | None = None,
|
| 1594 |
+
attention_mask: torch.Tensor | None = None,
|
| 1595 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1596 |
+
labels: torch.Tensor | None = None,
|
| 1597 |
+
output_hidden_states: bool | None = None,
|
| 1598 |
+
output_attentions: bool | None = None,
|
| 1599 |
+
return_dict: bool | None = None,
|
| 1600 |
+
) -> TokenClassifierOutput | tuple[torch.Tensor, ...]:
|
| 1601 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1602 |
+
outputs = self.encoder(
|
| 1603 |
+
input_ids=input_ids,
|
| 1604 |
+
attention_mask=attention_mask,
|
| 1605 |
+
inputs_embeds=inputs_embeds,
|
| 1606 |
+
output_hidden_states=output_hidden_states,
|
| 1607 |
+
output_attentions=output_attentions,
|
| 1608 |
+
return_dict=True,
|
| 1609 |
+
)
|
| 1610 |
+
sequence_output = outputs.last_hidden_state
|
| 1611 |
+
logits = self.classifier(sequence_output)
|
| 1612 |
+
|
| 1613 |
+
loss = None
|
| 1614 |
+
if labels is not None:
|
| 1615 |
+
labels = labels.to(logits.device)
|
| 1616 |
+
loss = self.loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1617 |
+
|
| 1618 |
+
if not return_dict:
|
| 1619 |
+
output = (logits, *outputs.to_tuple()[1:])
|
| 1620 |
+
return (loss, *output) if loss is not None else output
|
| 1621 |
+
|
| 1622 |
+
return TokenClassifierOutput(
|
| 1623 |
+
loss=loss,
|
| 1624 |
+
logits=logits,
|
| 1625 |
+
hidden_states=outputs.hidden_states,
|
| 1626 |
+
attentions=outputs.attentions,
|
| 1627 |
+
)
|
fastplms/models/ttt.py
ADDED
|
@@ -0,0 +1,866 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import math
|
| 5 |
+
import numbers
|
| 6 |
+
import typing as T
|
| 7 |
+
from dataclasses import asdict, dataclass, fields
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
|
| 13 |
+
_STANDARD_AMINO_ACIDS = "ACDEFGHIKLMNPQRSTVWY"
|
| 14 |
+
_TTT_SERIALIZATION_VERSION = 1
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class TTTConfig:
|
| 19 |
+
lr: float = 4e-4
|
| 20 |
+
steps: int = 30
|
| 21 |
+
ags: int = 16
|
| 22 |
+
batch_size: int = 2
|
| 23 |
+
mask_ratio: float = 0.15
|
| 24 |
+
crop_size: int = 1024
|
| 25 |
+
bert_leave_prob: float = 0.1
|
| 26 |
+
bert_replace_prob: float = 0.1
|
| 27 |
+
optimizer: str = "sgd"
|
| 28 |
+
momentum: float = 0.0
|
| 29 |
+
weight_decay: float = 0.0
|
| 30 |
+
seed: int | None = 0
|
| 31 |
+
lora_rank: int = 8
|
| 32 |
+
lora_alpha: float = 32.0
|
| 33 |
+
lora_target_replace_module: str | None = None
|
| 34 |
+
lora_target_modules: tuple[str, ...] | None = None
|
| 35 |
+
initial_state_reset: bool = True
|
| 36 |
+
automatic_best_state_reset: bool = False
|
| 37 |
+
eval_each_step: bool = False
|
| 38 |
+
gradient_clip: bool = False
|
| 39 |
+
gradient_clip_max_norm: float = 1.0
|
| 40 |
+
|
| 41 |
+
def __post_init__(self) -> None:
|
| 42 |
+
self.verify()
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_kwargs(cls, **kwargs: T.Any) -> TTTConfig:
|
| 46 |
+
valid_names = {field.name for field in fields(cls)}
|
| 47 |
+
unknown_names = set(kwargs) - valid_names
|
| 48 |
+
if unknown_names:
|
| 49 |
+
raise ValueError(f"Unknown TTTConfig fields: {sorted(unknown_names)}")
|
| 50 |
+
# JSON has no tuple type. Normalize the serialized representation while
|
| 51 |
+
# keeping the public constructor and runtime overrides type-strict.
|
| 52 |
+
if isinstance(kwargs.get("lora_target_modules"), list):
|
| 53 |
+
kwargs["lora_target_modules"] = tuple(kwargs["lora_target_modules"])
|
| 54 |
+
return cls(**kwargs)
|
| 55 |
+
|
| 56 |
+
def merged(self, overrides: T.Mapping[str, T.Any] | TTTConfig | None) -> TTTConfig:
|
| 57 |
+
if overrides is None:
|
| 58 |
+
return self
|
| 59 |
+
if isinstance(overrides, TTTConfig):
|
| 60 |
+
return overrides
|
| 61 |
+
values = {field.name: self.__dict__[field.name] for field in fields(self)}
|
| 62 |
+
for name, value in overrides.items():
|
| 63 |
+
if name not in values:
|
| 64 |
+
raise ValueError(f"Unknown TTTConfig field: {name}")
|
| 65 |
+
values[name] = value
|
| 66 |
+
return TTTConfig(**values)
|
| 67 |
+
|
| 68 |
+
def to_dict(self) -> dict[str, T.Any]:
|
| 69 |
+
return asdict(self)
|
| 70 |
+
|
| 71 |
+
def verify(self) -> None:
|
| 72 |
+
numeric_fields = {
|
| 73 |
+
"lr": self.lr,
|
| 74 |
+
"mask_ratio": self.mask_ratio,
|
| 75 |
+
"lora_alpha": self.lora_alpha,
|
| 76 |
+
"bert_leave_prob": self.bert_leave_prob,
|
| 77 |
+
"bert_replace_prob": self.bert_replace_prob,
|
| 78 |
+
"gradient_clip_max_norm": self.gradient_clip_max_norm,
|
| 79 |
+
"momentum": self.momentum,
|
| 80 |
+
"weight_decay": self.weight_decay,
|
| 81 |
+
}
|
| 82 |
+
for name, value in numeric_fields.items():
|
| 83 |
+
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
| 84 |
+
raise TypeError(f"TTT {name} must be a real number.")
|
| 85 |
+
if not math.isfinite(float(value)):
|
| 86 |
+
raise ValueError(f"TTT {name} must be finite.")
|
| 87 |
+
|
| 88 |
+
integer_fields = {
|
| 89 |
+
"steps": self.steps,
|
| 90 |
+
"ags": self.ags,
|
| 91 |
+
"batch_size": self.batch_size,
|
| 92 |
+
"crop_size": self.crop_size,
|
| 93 |
+
"lora_rank": self.lora_rank,
|
| 94 |
+
}
|
| 95 |
+
for name, value in integer_fields.items():
|
| 96 |
+
if isinstance(value, bool) or not isinstance(value, int):
|
| 97 |
+
raise TypeError(f"TTT {name} must be an integer.")
|
| 98 |
+
|
| 99 |
+
if self.seed is not None and (
|
| 100 |
+
isinstance(self.seed, bool) or not isinstance(self.seed, int)
|
| 101 |
+
):
|
| 102 |
+
raise TypeError("TTT seed must be None or an integer.")
|
| 103 |
+
|
| 104 |
+
boolean_fields = {
|
| 105 |
+
"initial_state_reset": self.initial_state_reset,
|
| 106 |
+
"automatic_best_state_reset": self.automatic_best_state_reset,
|
| 107 |
+
"eval_each_step": self.eval_each_step,
|
| 108 |
+
"gradient_clip": self.gradient_clip,
|
| 109 |
+
}
|
| 110 |
+
for name, value in boolean_fields.items():
|
| 111 |
+
if type(value) is not bool:
|
| 112 |
+
raise TypeError(f"TTT {name} must be a boolean.")
|
| 113 |
+
|
| 114 |
+
if self.lr <= 0.0:
|
| 115 |
+
raise ValueError("TTT learning rate must be positive.")
|
| 116 |
+
if self.steps < 1:
|
| 117 |
+
raise ValueError("TTT steps must be >= 1.")
|
| 118 |
+
if self.ags < 1:
|
| 119 |
+
raise ValueError("TTT gradient accumulation steps must be >= 1.")
|
| 120 |
+
if self.batch_size < 1:
|
| 121 |
+
raise ValueError("TTT batch_size must be >= 1.")
|
| 122 |
+
if not 0.0 < self.mask_ratio <= 1.0:
|
| 123 |
+
raise ValueError("TTT mask_ratio must be in (0, 1].")
|
| 124 |
+
if self.crop_size < 1:
|
| 125 |
+
raise ValueError("TTT crop_size must be >= 1.")
|
| 126 |
+
if self.lora_rank < 1:
|
| 127 |
+
raise ValueError("TTT v1 is LoRA-only, so lora_rank must be >= 1.")
|
| 128 |
+
if self.lora_alpha <= 0.0:
|
| 129 |
+
raise ValueError("TTT lora_alpha must be positive.")
|
| 130 |
+
if not isinstance(self.optimizer, str):
|
| 131 |
+
raise TypeError("TTT optimizer must be a string.")
|
| 132 |
+
if self.optimizer not in {"adamw", "sgd"}:
|
| 133 |
+
raise ValueError("TTT optimizer must be 'adamw' or 'sgd'.")
|
| 134 |
+
if self.momentum < 0.0:
|
| 135 |
+
raise ValueError("TTT momentum must be non-negative.")
|
| 136 |
+
if self.weight_decay < 0.0:
|
| 137 |
+
raise ValueError("TTT weight_decay must be non-negative.")
|
| 138 |
+
if not 0.0 <= self.bert_leave_prob <= 1.0:
|
| 139 |
+
raise ValueError("bert_leave_prob must be in [0, 1].")
|
| 140 |
+
if not 0.0 <= self.bert_replace_prob <= 1.0:
|
| 141 |
+
raise ValueError("bert_replace_prob must be in [0, 1].")
|
| 142 |
+
if self.bert_leave_prob + self.bert_replace_prob > 1.0:
|
| 143 |
+
raise ValueError("bert_leave_prob + bert_replace_prob must be <= 1.")
|
| 144 |
+
if self.gradient_clip and self.gradient_clip_max_norm <= 0.0:
|
| 145 |
+
raise ValueError("gradient_clip_max_norm must be positive.")
|
| 146 |
+
if self.lora_target_replace_module is not None:
|
| 147 |
+
if not isinstance(self.lora_target_replace_module, str):
|
| 148 |
+
raise TypeError("lora_target_replace_module must be None or a string.")
|
| 149 |
+
if not self.lora_target_replace_module.strip():
|
| 150 |
+
raise ValueError("lora_target_replace_module must not be empty.")
|
| 151 |
+
if self.lora_target_modules is not None:
|
| 152 |
+
if not isinstance(self.lora_target_modules, tuple):
|
| 153 |
+
raise TypeError("lora_target_modules must be None or a tuple of strings.")
|
| 154 |
+
if not self.lora_target_modules:
|
| 155 |
+
raise ValueError("lora_target_modules must not be empty.")
|
| 156 |
+
if any(not isinstance(name, str) for name in self.lora_target_modules):
|
| 157 |
+
raise TypeError("lora_target_modules must contain only strings.")
|
| 158 |
+
if any(not name.strip() for name in self.lora_target_modules):
|
| 159 |
+
raise ValueError(
|
| 160 |
+
"lora_target_modules must contain only non-empty strings."
|
| 161 |
+
)
|
| 162 |
+
if len(set(self.lora_target_modules)) != len(self.lora_target_modules):
|
| 163 |
+
raise ValueError("lora_target_modules must not contain duplicates.")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class LoraInjectedLinear(nn.Module):
|
| 167 |
+
"""ProteinTTT-compatible low-rank adapter.
|
| 168 |
+
|
| 169 |
+
``alpha`` is the direct adapter-output multiplier used by the pinned
|
| 170 |
+
ProteinTTT ``inject_trainable_lora(..., scale=lora_alpha)`` contract. It
|
| 171 |
+
is intentionally not divided by ``rank`` as it would be in the common
|
| 172 |
+
PEFT LoRA convention.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(
|
| 176 |
+
self,
|
| 177 |
+
linear: nn.Module,
|
| 178 |
+
rank: int,
|
| 179 |
+
alpha: float,
|
| 180 |
+
generator: torch.Generator | None = None,
|
| 181 |
+
) -> None:
|
| 182 |
+
super().__init__()
|
| 183 |
+
weight = linear._parameters.get("weight")
|
| 184 |
+
if not isinstance(weight, torch.Tensor):
|
| 185 |
+
raise TypeError("LoRA targets must expose a tensor weight parameter.")
|
| 186 |
+
if weight.ndim != 2:
|
| 187 |
+
raise ValueError("LoRA can only wrap 2D linear weights.")
|
| 188 |
+
self.linear = linear
|
| 189 |
+
self.linear.requires_grad_(False)
|
| 190 |
+
self.rank = rank
|
| 191 |
+
# ProteinTTT names this setting ``lora_alpha`` but passes it directly
|
| 192 |
+
# to cloneofsimo/lora's ``scale`` argument. Preserve that numerical
|
| 193 |
+
# contract for parity and for saved FastPLMs TTT configurations.
|
| 194 |
+
self.scale = alpha
|
| 195 |
+
in_features = weight.shape[1]
|
| 196 |
+
out_features = weight.shape[0]
|
| 197 |
+
# ``nn.Linear`` initializes from the process-global CPU generator. Preserve
|
| 198 |
+
# that state when TTT supplies its own generator so lazy adapter injection
|
| 199 |
+
# is reproducible without perturbing the caller's RNG stream.
|
| 200 |
+
with torch.random.fork_rng(devices=[], enabled=generator is not None):
|
| 201 |
+
self.lora_down = nn.Linear(in_features, rank, bias=False, dtype=torch.float32)
|
| 202 |
+
self.lora_up = nn.Linear(rank, out_features, bias=False, dtype=torch.float32)
|
| 203 |
+
nn.init.normal_(self.lora_down.weight, std=1.0 / rank, generator=generator)
|
| 204 |
+
nn.init.zeros_(self.lora_up.weight)
|
| 205 |
+
self.lora_down.to(device=weight.device)
|
| 206 |
+
self.lora_up.to(device=weight.device)
|
| 207 |
+
self.register_buffer(
|
| 208 |
+
"_ttt_initial_lora_down",
|
| 209 |
+
self.lora_down.weight.detach().clone(),
|
| 210 |
+
persistent=True,
|
| 211 |
+
)
|
| 212 |
+
self.register_buffer(
|
| 213 |
+
"_ttt_initial_lora_up",
|
| 214 |
+
self.lora_up.weight.detach().clone(),
|
| 215 |
+
persistent=True,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def weight(self) -> torch.Tensor:
|
| 220 |
+
return self.linear._parameters["weight"]
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def bias(self) -> torch.Tensor | None:
|
| 224 |
+
return self.linear._parameters["bias"]
|
| 225 |
+
|
| 226 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 227 |
+
base = self.linear(x)
|
| 228 |
+
delta = self.lora_up(self.lora_down(x.to(dtype=torch.float32))) * self.scale
|
| 229 |
+
return base + delta.to(dtype=base.dtype)
|
| 230 |
+
|
| 231 |
+
def reset_lora_parameters(self) -> None:
|
| 232 |
+
with torch.no_grad():
|
| 233 |
+
self.lora_down.weight.copy_(self._ttt_initial_lora_down)
|
| 234 |
+
self.lora_up.weight.copy_(self._ttt_initial_lora_up)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class FastPLMTestTimeTrainingMixin:
|
| 238 |
+
def init_ttt(self, ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None) -> None:
|
| 239 |
+
base_config = self.__dict__.get("_ttt_cfg")
|
| 240 |
+
if base_config is None:
|
| 241 |
+
base_config = TTTConfig()
|
| 242 |
+
if not isinstance(base_config, TTTConfig):
|
| 243 |
+
raise TypeError("Existing TTT configuration must be a TTTConfig instance.")
|
| 244 |
+
configured = base_config.merged(ttt_config)
|
| 245 |
+
serialized = getattr(getattr(self, "config", None), "fastplms_ttt", None)
|
| 246 |
+
serialized_initialized = False
|
| 247 |
+
if serialized is not None:
|
| 248 |
+
if not isinstance(serialized, T.Mapping):
|
| 249 |
+
raise ValueError("config.fastplms_ttt must be a mapping.")
|
| 250 |
+
version = serialized.get("version")
|
| 251 |
+
if version != _TTT_SERIALIZATION_VERSION:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
"Unsupported FastPLMs TTT serialization version "
|
| 254 |
+
f"{version!r}; expected {_TTT_SERIALIZATION_VERSION}."
|
| 255 |
+
)
|
| 256 |
+
serialized_config = serialized.get("config")
|
| 257 |
+
if not isinstance(serialized_config, T.Mapping):
|
| 258 |
+
raise ValueError("Serialized FastPLMs TTT state is missing its config mapping.")
|
| 259 |
+
configured = TTTConfig.from_kwargs(**dict(serialized_config))
|
| 260 |
+
initialized_value = serialized.get("initialized", False)
|
| 261 |
+
if type(initialized_value) is not bool:
|
| 262 |
+
raise ValueError("Serialized FastPLMs TTT initialized flag must be a boolean.")
|
| 263 |
+
serialized_initialized = initialized_value
|
| 264 |
+
|
| 265 |
+
self._ttt_cfg = configured
|
| 266 |
+
self._ttt_cfg.verify()
|
| 267 |
+
self._ttt_initialized = False
|
| 268 |
+
if serialized_initialized:
|
| 269 |
+
self._ttt_inject_lora()
|
| 270 |
+
self._ttt_initialized = True
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def ttt_config(self) -> TTTConfig:
|
| 274 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 275 |
+
self.init_ttt()
|
| 276 |
+
return self._ttt_cfg
|
| 277 |
+
|
| 278 |
+
def _ttt_get_trainable_modules(self) -> list[nn.Module]:
|
| 279 |
+
return [self]
|
| 280 |
+
|
| 281 |
+
def _ttt_get_frozen_modules(self) -> list[nn.Module]:
|
| 282 |
+
return []
|
| 283 |
+
|
| 284 |
+
def _ttt_tokenize(
|
| 285 |
+
self,
|
| 286 |
+
seq: str | list[str] | None = None,
|
| 287 |
+
input_ids: torch.Tensor | None = None,
|
| 288 |
+
**kwargs: T.Any,
|
| 289 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 290 |
+
del kwargs
|
| 291 |
+
if input_ids is not None:
|
| 292 |
+
return input_ids
|
| 293 |
+
if seq is None:
|
| 294 |
+
raise ValueError("Pass either seq or input_ids for TTT.")
|
| 295 |
+
tokenized = self.tokenizer(seq, return_tensors="pt", padding=True)
|
| 296 |
+
return tokenized["input_ids"]
|
| 297 |
+
|
| 298 |
+
def _ttt_mask_token(self) -> int:
|
| 299 |
+
return int(self.tokenizer.mask_token_id)
|
| 300 |
+
|
| 301 |
+
def _ttt_padding_token(self) -> int:
|
| 302 |
+
return int(self.tokenizer.pad_token_id)
|
| 303 |
+
|
| 304 |
+
def _ttt_replacement_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 305 |
+
tokenizer = self.tokenizer
|
| 306 |
+
special_ids = set(tokenizer.all_special_ids)
|
| 307 |
+
vocab_size = int(self.config.vocab_size)
|
| 308 |
+
unknown_id = getattr(tokenizer, "unk_token_id", None)
|
| 309 |
+
if unknown_id is not None:
|
| 310 |
+
special_ids.add(int(unknown_id))
|
| 311 |
+
|
| 312 |
+
vocab: T.Mapping[str, T.Any] = {}
|
| 313 |
+
get_vocab = getattr(tokenizer, "get_vocab", None)
|
| 314 |
+
if callable(get_vocab):
|
| 315 |
+
vocab = get_vocab()
|
| 316 |
+
elif isinstance(getattr(tokenizer, "vocab", None), T.Mapping):
|
| 317 |
+
vocab = tokenizer.vocab
|
| 318 |
+
elif isinstance(getattr(tokenizer, "_token_to_id", None), T.Mapping):
|
| 319 |
+
vocab = tokenizer._token_to_id
|
| 320 |
+
|
| 321 |
+
ids: list[int] = []
|
| 322 |
+
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
|
| 323 |
+
for amino_acid in _STANDARD_AMINO_ACIDS:
|
| 324 |
+
token_id = convert(amino_acid) if callable(convert) else vocab.get(amino_acid)
|
| 325 |
+
if (
|
| 326 |
+
isinstance(token_id, int)
|
| 327 |
+
and 0 <= token_id < vocab_size
|
| 328 |
+
and token_id not in special_ids
|
| 329 |
+
and token_id not in ids
|
| 330 |
+
):
|
| 331 |
+
ids.append(token_id)
|
| 332 |
+
if not ids:
|
| 333 |
+
raise ValueError(
|
| 334 |
+
"TTT could not resolve any canonical amino-acid token IDs from the tokenizer; "
|
| 335 |
+
"refusing to sample arbitrary or reserved vocabulary entries."
|
| 336 |
+
)
|
| 337 |
+
return torch.tensor(ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 338 |
+
|
| 339 |
+
def _ttt_predict_logits(
|
| 340 |
+
self,
|
| 341 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 342 |
+
**kwargs: T.Any,
|
| 343 |
+
) -> torch.Tensor:
|
| 344 |
+
del kwargs
|
| 345 |
+
if isinstance(batch, dict):
|
| 346 |
+
output = self(**batch)
|
| 347 |
+
return output.logits
|
| 348 |
+
attention_mask = batch.ne(self._ttt_padding_token())
|
| 349 |
+
output = self(input_ids=batch, attention_mask=attention_mask)
|
| 350 |
+
return output.logits
|
| 351 |
+
|
| 352 |
+
def _ttt_eval_step(
|
| 353 |
+
self,
|
| 354 |
+
step: int,
|
| 355 |
+
loss: float,
|
| 356 |
+
seq: str | list[str] | None = None,
|
| 357 |
+
input_ids: torch.Tensor | None = None,
|
| 358 |
+
**kwargs: T.Any,
|
| 359 |
+
) -> tuple[dict[str, T.Any], float | None]:
|
| 360 |
+
del step, loss, seq, input_ids, kwargs
|
| 361 |
+
return {}, None
|
| 362 |
+
|
| 363 |
+
def _ttt_is_lora_target(
|
| 364 |
+
self,
|
| 365 |
+
name: str,
|
| 366 |
+
full_name: str,
|
| 367 |
+
module: nn.Module,
|
| 368 |
+
active: bool,
|
| 369 |
+
target_modules: tuple[str, ...] | None,
|
| 370 |
+
) -> bool:
|
| 371 |
+
if not active:
|
| 372 |
+
return False
|
| 373 |
+
if isinstance(module, LoraInjectedLinear):
|
| 374 |
+
return False
|
| 375 |
+
if (
|
| 376 |
+
target_modules is not None
|
| 377 |
+
and name not in target_modules
|
| 378 |
+
and full_name not in target_modules
|
| 379 |
+
):
|
| 380 |
+
return False
|
| 381 |
+
if isinstance(module, nn.Linear):
|
| 382 |
+
return True
|
| 383 |
+
if "weight" not in module._parameters:
|
| 384 |
+
return False
|
| 385 |
+
weight = module._parameters["weight"]
|
| 386 |
+
if weight is None or weight.ndim != 2:
|
| 387 |
+
return False
|
| 388 |
+
return "Linear" in module.__class__.__name__
|
| 389 |
+
|
| 390 |
+
def _ttt_inject_lora(self) -> int:
|
| 391 |
+
cfg = self.ttt_config
|
| 392 |
+
cfg.verify()
|
| 393 |
+
target_class = cfg.lora_target_replace_module
|
| 394 |
+
target_modules = cfg.lora_target_modules
|
| 395 |
+
wrapped = 0
|
| 396 |
+
generator = None
|
| 397 |
+
if cfg.seed is not None:
|
| 398 |
+
generator = torch.Generator(device="cpu")
|
| 399 |
+
generator.manual_seed(cfg.seed)
|
| 400 |
+
|
| 401 |
+
def inject(module: nn.Module, prefix: str, active: bool) -> None:
|
| 402 |
+
nonlocal wrapped
|
| 403 |
+
for name, child in list(module.named_children()):
|
| 404 |
+
full_name = f"{prefix}.{name}" if prefix else name
|
| 405 |
+
child_active = active
|
| 406 |
+
if target_class is not None:
|
| 407 |
+
child_active = active or child.__class__.__name__ == target_class
|
| 408 |
+
if self._ttt_is_lora_target(name, full_name, child, child_active, target_modules):
|
| 409 |
+
setattr(
|
| 410 |
+
module,
|
| 411 |
+
name,
|
| 412 |
+
LoraInjectedLinear(
|
| 413 |
+
child,
|
| 414 |
+
rank=cfg.lora_rank,
|
| 415 |
+
alpha=cfg.lora_alpha,
|
| 416 |
+
generator=generator,
|
| 417 |
+
),
|
| 418 |
+
)
|
| 419 |
+
wrapped += 1
|
| 420 |
+
continue
|
| 421 |
+
inject(child, full_name, child_active)
|
| 422 |
+
|
| 423 |
+
for trainable_module in self._ttt_get_trainable_modules():
|
| 424 |
+
inject(trainable_module, "", target_class is None)
|
| 425 |
+
if wrapped == 0:
|
| 426 |
+
raise ValueError("TTT LoRA injection did not find any target modules.")
|
| 427 |
+
return wrapped
|
| 428 |
+
|
| 429 |
+
def _ttt_lora_modules(self) -> list[LoraInjectedLinear]:
|
| 430 |
+
return [module for module in self.modules() if isinstance(module, LoraInjectedLinear)]
|
| 431 |
+
|
| 432 |
+
def _ttt_lora_parameters(self) -> list[nn.Parameter]:
|
| 433 |
+
params: list[nn.Parameter] = []
|
| 434 |
+
for module in self._ttt_lora_modules():
|
| 435 |
+
params.extend(module.lora_down.parameters())
|
| 436 |
+
params.extend(module.lora_up.parameters())
|
| 437 |
+
if not params:
|
| 438 |
+
raise RuntimeError("TTT has no LoRA parameters.")
|
| 439 |
+
return params
|
| 440 |
+
|
| 441 |
+
def _ttt_snapshot_lora_state(self) -> list[dict[str, torch.Tensor]]:
|
| 442 |
+
snapshot = []
|
| 443 |
+
for module in self._ttt_lora_modules():
|
| 444 |
+
snapshot.append(
|
| 445 |
+
{
|
| 446 |
+
"lora_down.weight": module.lora_down.weight.detach().clone(),
|
| 447 |
+
"lora_up.weight": module.lora_up.weight.detach().clone(),
|
| 448 |
+
}
|
| 449 |
+
)
|
| 450 |
+
if not snapshot:
|
| 451 |
+
raise RuntimeError("TTT has no LoRA state to snapshot.")
|
| 452 |
+
return snapshot
|
| 453 |
+
|
| 454 |
+
def _ttt_restore_lora_state(self, state: list[dict[str, torch.Tensor]]) -> None:
|
| 455 |
+
modules = self._ttt_lora_modules()
|
| 456 |
+
if len(modules) != len(state):
|
| 457 |
+
raise RuntimeError("TTT LoRA state/module count mismatch.")
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
for module, module_state in zip(modules, state, strict=True):
|
| 460 |
+
module.lora_down.weight.copy_(module_state["lora_down.weight"])
|
| 461 |
+
module.lora_up.weight.copy_(module_state["lora_up.weight"])
|
| 462 |
+
|
| 463 |
+
def _ttt_ensure_initialized(self) -> None:
|
| 464 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 465 |
+
self.init_ttt()
|
| 466 |
+
if self._ttt_initialized:
|
| 467 |
+
return
|
| 468 |
+
self._ttt_inject_lora()
|
| 469 |
+
self._ttt_initialized = True
|
| 470 |
+
|
| 471 |
+
def ttt_reset(self) -> None:
|
| 472 |
+
self._ttt_ensure_initialized()
|
| 473 |
+
for module in self._ttt_lora_modules():
|
| 474 |
+
module.reset_lora_parameters()
|
| 475 |
+
|
| 476 |
+
def _ttt_serialized_contract(self) -> dict[str, T.Any]:
|
| 477 |
+
return {
|
| 478 |
+
"version": _TTT_SERIALIZATION_VERSION,
|
| 479 |
+
"initialized": bool(self._ttt_initialized),
|
| 480 |
+
"config": self.ttt_config.to_dict(),
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
def save_pretrained(self, save_directory: T.Any, *args: T.Any, **kwargs: T.Any) -> T.Any:
|
| 484 |
+
"""Save initialized adapters, their reset baseline, and the TTT config.
|
| 485 |
+
|
| 486 |
+
Adapter injection changes the module tree, so the serialized config must
|
| 487 |
+
reconstruct that tree before Transformers loads the state dict. Models
|
| 488 |
+
whose own state-dict hooks omit their trainable TTT modules fail closed
|
| 489 |
+
instead of producing an artifact that cannot restore the adaptation.
|
| 490 |
+
"""
|
| 491 |
+
|
| 492 |
+
if self._ttt_initialized:
|
| 493 |
+
state_keys = set(self.state_dict())
|
| 494 |
+
missing_adapter_keys = [
|
| 495 |
+
name
|
| 496 |
+
for name, _ in self.named_parameters()
|
| 497 |
+
if ".lora_" in name and name not in state_keys
|
| 498 |
+
]
|
| 499 |
+
if missing_adapter_keys:
|
| 500 |
+
raise RuntimeError(
|
| 501 |
+
"This model attaches TTT adapters to transient modules that its "
|
| 502 |
+
"checkpoint excludes, so save_pretrained cannot persist the adapted "
|
| 503 |
+
"state safely. Reset the model or use a model-specific adapter export."
|
| 504 |
+
)
|
| 505 |
+
self.config.fastplms_ttt = self._ttt_serialized_contract()
|
| 506 |
+
return super().save_pretrained(save_directory, *args, **kwargs)
|
| 507 |
+
|
| 508 |
+
def _ttt_make_optimizer(self) -> torch.optim.Optimizer:
|
| 509 |
+
cfg = self.ttt_config
|
| 510 |
+
params = self._ttt_lora_parameters()
|
| 511 |
+
if cfg.optimizer == "sgd":
|
| 512 |
+
return torch.optim.SGD(
|
| 513 |
+
params,
|
| 514 |
+
lr=cfg.lr,
|
| 515 |
+
momentum=cfg.momentum,
|
| 516 |
+
weight_decay=cfg.weight_decay,
|
| 517 |
+
)
|
| 518 |
+
return torch.optim.AdamW(params, lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 519 |
+
|
| 520 |
+
def _ttt_to_device(
|
| 521 |
+
self,
|
| 522 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 523 |
+
device: torch.device,
|
| 524 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 525 |
+
if isinstance(batch, dict):
|
| 526 |
+
return {name: tensor.to(device) for name, tensor in batch.items()}
|
| 527 |
+
return batch.to(device)
|
| 528 |
+
|
| 529 |
+
def _ttt_input_ids_from_batch(
|
| 530 |
+
self,
|
| 531 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 532 |
+
) -> torch.Tensor:
|
| 533 |
+
if isinstance(batch, dict):
|
| 534 |
+
return batch["input_ids"]
|
| 535 |
+
return batch
|
| 536 |
+
|
| 537 |
+
def _ttt_set_input_ids(
|
| 538 |
+
self,
|
| 539 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 540 |
+
input_ids: torch.Tensor,
|
| 541 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 542 |
+
if isinstance(batch, dict):
|
| 543 |
+
updated = dict(batch)
|
| 544 |
+
updated["input_ids"] = input_ids
|
| 545 |
+
return updated
|
| 546 |
+
return input_ids
|
| 547 |
+
|
| 548 |
+
def _ttt_non_special_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 549 |
+
residue_ids = self._ttt_replacement_tokens(input_ids)
|
| 550 |
+
return torch.isin(input_ids, residue_ids)
|
| 551 |
+
|
| 552 |
+
def _ttt_validate_tokenized_batch(
|
| 553 |
+
self,
|
| 554 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 555 |
+
) -> None:
|
| 556 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 557 |
+
if input_ids.ndim != 2 or input_ids.shape[0] == 0 or input_ids.shape[1] == 0:
|
| 558 |
+
raise ValueError(
|
| 559 |
+
"TTT input_ids must have non-empty shape (batch, sequence); got "
|
| 560 |
+
f"{tuple(input_ids.shape)}."
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
if str(getattr(self.config, "model_type", "")) == "dplm2":
|
| 564 |
+
tokenizer = self.tokenizer
|
| 565 |
+
token_to_id = getattr(tokenizer, "_token_to_id", {})
|
| 566 |
+
struct_cls_token = getattr(tokenizer, "struct_cls_token", None)
|
| 567 |
+
struct_boundary = token_to_id.get(struct_cls_token)
|
| 568 |
+
if struct_boundary is None:
|
| 569 |
+
raise ValueError(
|
| 570 |
+
"DPLM2 TTT could not resolve the structure-token boundary safely."
|
| 571 |
+
)
|
| 572 |
+
pad_token = self._ttt_padding_token()
|
| 573 |
+
generic_aa_special_ids = torch.tensor(
|
| 574 |
+
[int(self.config.vocab_size) + offset for offset in range(4)],
|
| 575 |
+
device=input_ids.device,
|
| 576 |
+
dtype=input_ids.dtype,
|
| 577 |
+
)
|
| 578 |
+
is_structure = input_ids.ge(int(struct_boundary)) & input_ids.ne(pad_token)
|
| 579 |
+
is_structure &= ~torch.isin(input_ids, generic_aa_special_ids)
|
| 580 |
+
if bool(is_structure.any()):
|
| 581 |
+
raise ValueError(
|
| 582 |
+
"DPLM2 TTT currently supports amino-acid-only inputs. Packed or "
|
| 583 |
+
"structure-token inputs require a modality-specific corruption objective."
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
if isinstance(batch, dict) and "type_ids" in batch:
|
| 587 |
+
type_ids = batch["type_ids"]
|
| 588 |
+
attention_mask = batch.get("attention_mask", input_ids.ne(pad_token)).bool()
|
| 589 |
+
if bool(((type_ids == int(self.config.struct_type)) & attention_mask).any()):
|
| 590 |
+
raise ValueError(
|
| 591 |
+
"DPLM2 TTT currently supports amino-acid-only inputs; structure "
|
| 592 |
+
"type_ids are not accepted."
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if not bool(self._ttt_non_special_mask(input_ids).any()):
|
| 596 |
+
raise ValueError(
|
| 597 |
+
"TTT input contains no trainable biological residue tokens after excluding "
|
| 598 |
+
"padding, boundary, mask, and reserved tokens."
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
def _ttt_sample_crop(
|
| 602 |
+
self,
|
| 603 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 604 |
+
generator: torch.Generator,
|
| 605 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 606 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 607 |
+
cfg = self.ttt_config
|
| 608 |
+
if input_ids.shape[1] <= cfg.crop_size:
|
| 609 |
+
return batch
|
| 610 |
+
position_has_residue = self._ttt_non_special_mask(input_ids).any(dim=0).to(torch.int64)
|
| 611 |
+
prefix = F.pad(position_has_residue.cumsum(dim=0), (1, 0))
|
| 612 |
+
window_counts = prefix[cfg.crop_size :] - prefix[: -cfg.crop_size]
|
| 613 |
+
valid_starts = torch.where(window_counts > 0)[0]
|
| 614 |
+
if valid_starts.numel() == 0:
|
| 615 |
+
raise ValueError("TTT could not find a crop containing a biological residue token.")
|
| 616 |
+
selected = torch.randint(
|
| 617 |
+
valid_starts.numel(),
|
| 618 |
+
(1,),
|
| 619 |
+
generator=generator,
|
| 620 |
+
device=input_ids.device,
|
| 621 |
+
)
|
| 622 |
+
start = int(valid_starts[selected].item())
|
| 623 |
+
end = start + cfg.crop_size
|
| 624 |
+
if isinstance(batch, dict):
|
| 625 |
+
cropped = {}
|
| 626 |
+
for name, tensor in batch.items():
|
| 627 |
+
if tensor.ndim >= 2 and tensor.shape[1] == input_ids.shape[1]:
|
| 628 |
+
cropped[name] = tensor[:, start:end]
|
| 629 |
+
else:
|
| 630 |
+
cropped[name] = tensor
|
| 631 |
+
return cropped
|
| 632 |
+
return input_ids[:, start:end]
|
| 633 |
+
|
| 634 |
+
def _ttt_sample_batch(
|
| 635 |
+
self,
|
| 636 |
+
tokenized: torch.Tensor | dict[str, torch.Tensor],
|
| 637 |
+
generator: torch.Generator,
|
| 638 |
+
) -> tuple[torch.Tensor | dict[str, torch.Tensor], torch.Tensor]:
|
| 639 |
+
cfg = self.ttt_config
|
| 640 |
+
batch = self._ttt_sample_crop(tokenized, generator)
|
| 641 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 642 |
+
row_has_residue = self._ttt_non_special_mask(input_ids).any(dim=1)
|
| 643 |
+
eligible_rows = torch.where(row_has_residue)[0]
|
| 644 |
+
if eligible_rows.numel() == 0:
|
| 645 |
+
raise ValueError(
|
| 646 |
+
"TTT sampled batch contains no trainable biological residue tokens."
|
| 647 |
+
)
|
| 648 |
+
sampled_row_indices = torch.randint(
|
| 649 |
+
eligible_rows.numel(),
|
| 650 |
+
(cfg.batch_size,),
|
| 651 |
+
generator=generator,
|
| 652 |
+
device=input_ids.device,
|
| 653 |
+
)
|
| 654 |
+
rows = eligible_rows[sampled_row_indices]
|
| 655 |
+
if isinstance(batch, dict):
|
| 656 |
+
sampled: torch.Tensor | dict[str, torch.Tensor] = {}
|
| 657 |
+
for name, tensor in batch.items():
|
| 658 |
+
if tensor.ndim >= 1 and tensor.shape[0] == input_ids.shape[0]:
|
| 659 |
+
sampled[name] = tensor.index_select(0, rows)
|
| 660 |
+
else:
|
| 661 |
+
sampled[name] = tensor
|
| 662 |
+
else:
|
| 663 |
+
sampled = input_ids.index_select(0, rows)
|
| 664 |
+
|
| 665 |
+
sampled_ids = self._ttt_input_ids_from_batch(sampled)
|
| 666 |
+
labels = sampled_ids.clone()
|
| 667 |
+
non_special = self._ttt_non_special_mask(sampled_ids)
|
| 668 |
+
label_mask = torch.zeros_like(non_special)
|
| 669 |
+
for row_idx in range(sampled_ids.shape[0]):
|
| 670 |
+
candidate_positions = torch.where(non_special[row_idx])[0]
|
| 671 |
+
if candidate_positions.numel() == 0:
|
| 672 |
+
continue
|
| 673 |
+
num_mask = max(1, round(candidate_positions.numel() * cfg.mask_ratio))
|
| 674 |
+
order = torch.randperm(
|
| 675 |
+
candidate_positions.numel(),
|
| 676 |
+
generator=generator,
|
| 677 |
+
device=sampled_ids.device,
|
| 678 |
+
)
|
| 679 |
+
chosen = candidate_positions[order[:num_mask]]
|
| 680 |
+
label_mask[row_idx, chosen] = True
|
| 681 |
+
labels = labels.masked_fill(~label_mask, -100)
|
| 682 |
+
|
| 683 |
+
masked_ids = sampled_ids.clone()
|
| 684 |
+
chosen_positions = torch.where(label_mask)
|
| 685 |
+
if chosen_positions[0].numel() > 0:
|
| 686 |
+
random_values = torch.rand(
|
| 687 |
+
chosen_positions[0].shape,
|
| 688 |
+
generator=generator,
|
| 689 |
+
device=sampled_ids.device,
|
| 690 |
+
)
|
| 691 |
+
leave = random_values < cfg.bert_leave_prob
|
| 692 |
+
replace = (random_values >= cfg.bert_leave_prob) & (
|
| 693 |
+
random_values < cfg.bert_leave_prob + cfg.bert_replace_prob
|
| 694 |
+
)
|
| 695 |
+
mask = ~(leave | replace)
|
| 696 |
+
if mask.any():
|
| 697 |
+
masked_ids[
|
| 698 |
+
chosen_positions[0][mask],
|
| 699 |
+
chosen_positions[1][mask],
|
| 700 |
+
] = self._ttt_mask_token()
|
| 701 |
+
if replace.any():
|
| 702 |
+
replacement_tokens = self._ttt_replacement_tokens(sampled_ids)
|
| 703 |
+
replacement_idx = torch.randint(
|
| 704 |
+
replacement_tokens.shape[0],
|
| 705 |
+
(int(replace.sum().item()),),
|
| 706 |
+
generator=generator,
|
| 707 |
+
device=sampled_ids.device,
|
| 708 |
+
)
|
| 709 |
+
masked_ids[
|
| 710 |
+
chosen_positions[0][replace],
|
| 711 |
+
chosen_positions[1][replace],
|
| 712 |
+
] = replacement_tokens[replacement_idx]
|
| 713 |
+
|
| 714 |
+
return self._ttt_set_input_ids(sampled, masked_ids), labels
|
| 715 |
+
|
| 716 |
+
@contextlib.contextmanager
|
| 717 |
+
def _ttt_seed_scope(self, seed: int | None) -> T.Iterator[None]:
|
| 718 |
+
if seed is None:
|
| 719 |
+
yield
|
| 720 |
+
return
|
| 721 |
+
cuda_devices = sorted(
|
| 722 |
+
{
|
| 723 |
+
parameter.device.index
|
| 724 |
+
for parameter in self.parameters()
|
| 725 |
+
if parameter.device.type == "cuda" and parameter.device.index is not None
|
| 726 |
+
}
|
| 727 |
+
)
|
| 728 |
+
with torch.random.fork_rng(devices=cuda_devices):
|
| 729 |
+
torch.random.default_generator.manual_seed(seed)
|
| 730 |
+
for device_index in cuda_devices:
|
| 731 |
+
with torch.cuda.device(device_index):
|
| 732 |
+
torch.cuda.manual_seed(seed)
|
| 733 |
+
yield
|
| 734 |
+
|
| 735 |
+
def ttt(
|
| 736 |
+
self,
|
| 737 |
+
seq: str | list[str] | None = None,
|
| 738 |
+
input_ids: torch.Tensor | None = None,
|
| 739 |
+
ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None,
|
| 740 |
+
**kwargs: T.Any,
|
| 741 |
+
) -> dict[str, T.Any]:
|
| 742 |
+
if ttt_config is not None:
|
| 743 |
+
if "_ttt_initialized" in self.__dict__ and self._ttt_initialized:
|
| 744 |
+
next_cfg = self.ttt_config.merged(ttt_config)
|
| 745 |
+
current_cfg = self.ttt_config
|
| 746 |
+
if next_cfg.lora_rank != current_cfg.lora_rank:
|
| 747 |
+
raise ValueError(
|
| 748 |
+
"Changing lora_rank after TTT initialization is not supported."
|
| 749 |
+
)
|
| 750 |
+
if next_cfg.lora_alpha != current_cfg.lora_alpha:
|
| 751 |
+
raise ValueError(
|
| 752 |
+
"Changing lora_alpha after TTT initialization is not supported."
|
| 753 |
+
)
|
| 754 |
+
if (
|
| 755 |
+
next_cfg.lora_target_replace_module
|
| 756 |
+
!= current_cfg.lora_target_replace_module
|
| 757 |
+
):
|
| 758 |
+
raise ValueError(
|
| 759 |
+
"Changing LoRA target class after TTT initialization is not supported."
|
| 760 |
+
)
|
| 761 |
+
if next_cfg.lora_target_modules != current_cfg.lora_target_modules:
|
| 762 |
+
raise ValueError(
|
| 763 |
+
"Changing LoRA target modules after TTT initialization is not supported."
|
| 764 |
+
)
|
| 765 |
+
self._ttt_cfg = next_cfg
|
| 766 |
+
else:
|
| 767 |
+
# Family constructors preconfigure the attention class that may
|
| 768 |
+
# receive LoRA adapters. A first-call mapping changes only the
|
| 769 |
+
# requested fields; rebuilding from TTTConfig defaults here
|
| 770 |
+
# would erase that family target immediately before injection.
|
| 771 |
+
self._ttt_cfg = self.ttt_config.merged(ttt_config)
|
| 772 |
+
self._ttt_cfg.verify()
|
| 773 |
+
|
| 774 |
+
cfg = self.ttt_config
|
| 775 |
+
device = next(self.parameters()).device
|
| 776 |
+
tokenized = self._ttt_tokenize(seq=seq, input_ids=input_ids, **kwargs)
|
| 777 |
+
tokenized = self._ttt_to_device(tokenized, device)
|
| 778 |
+
self._ttt_validate_tokenized_batch(tokenized)
|
| 779 |
+
self._ttt_ensure_initialized()
|
| 780 |
+
if cfg.initial_state_reset:
|
| 781 |
+
self.ttt_reset()
|
| 782 |
+
|
| 783 |
+
generator_device = device if device.type == "cuda" else torch.device("cpu")
|
| 784 |
+
generator = torch.Generator(device=generator_device)
|
| 785 |
+
if cfg.seed is not None:
|
| 786 |
+
generator.manual_seed(cfg.seed)
|
| 787 |
+
|
| 788 |
+
module_modes = {module: module.training for module in self.modules()}
|
| 789 |
+
requires_grad = {param: param.requires_grad for param in self.parameters()}
|
| 790 |
+
losses: list[float] = []
|
| 791 |
+
step_metrics: list[dict[str, T.Any]] = []
|
| 792 |
+
best_state: list[dict[str, torch.Tensor]] | None = None
|
| 793 |
+
best_metric: float | None = None
|
| 794 |
+
best_step = 0
|
| 795 |
+
|
| 796 |
+
with self._ttt_seed_scope(cfg.seed):
|
| 797 |
+
try:
|
| 798 |
+
self.train()
|
| 799 |
+
for param in self.parameters():
|
| 800 |
+
param.requires_grad_(False)
|
| 801 |
+
for param in self._ttt_lora_parameters():
|
| 802 |
+
param.requires_grad_(True)
|
| 803 |
+
|
| 804 |
+
optimizer = self._ttt_make_optimizer()
|
| 805 |
+
optimizer.zero_grad(set_to_none=True)
|
| 806 |
+
total_micro_steps = cfg.steps * cfg.ags
|
| 807 |
+
for micro_step in range(total_micro_steps):
|
| 808 |
+
batch, labels = self._ttt_sample_batch(tokenized, generator)
|
| 809 |
+
if not bool(labels.ne(-100).any()):
|
| 810 |
+
raise RuntimeError(
|
| 811 |
+
"TTT produced an all-ignored label batch; refusing a NaN update."
|
| 812 |
+
)
|
| 813 |
+
logits = self._ttt_predict_logits(batch, **kwargs)
|
| 814 |
+
labels = labels.to(device=logits.device)
|
| 815 |
+
loss = F.cross_entropy(
|
| 816 |
+
logits.reshape(-1, logits.shape[-1]),
|
| 817 |
+
labels.reshape(-1),
|
| 818 |
+
ignore_index=-100,
|
| 819 |
+
)
|
| 820 |
+
if not bool(torch.isfinite(loss)):
|
| 821 |
+
raise FloatingPointError(
|
| 822 |
+
f"TTT loss is non-finite at micro-step {micro_step + 1}."
|
| 823 |
+
)
|
| 824 |
+
(loss / cfg.ags).backward()
|
| 825 |
+
if (micro_step + 1) % cfg.ags != 0:
|
| 826 |
+
continue
|
| 827 |
+
|
| 828 |
+
if cfg.gradient_clip:
|
| 829 |
+
torch.nn.utils.clip_grad_norm_(
|
| 830 |
+
self._ttt_lora_parameters(),
|
| 831 |
+
cfg.gradient_clip_max_norm,
|
| 832 |
+
)
|
| 833 |
+
optimizer.step()
|
| 834 |
+
optimizer.zero_grad(set_to_none=True)
|
| 835 |
+
step = (micro_step + 1) // cfg.ags
|
| 836 |
+
loss_value = float(loss.detach().item())
|
| 837 |
+
losses.append(loss_value)
|
| 838 |
+
if cfg.eval_each_step:
|
| 839 |
+
metrics, metric = self._ttt_eval_step(
|
| 840 |
+
step=step,
|
| 841 |
+
loss=loss_value,
|
| 842 |
+
seq=seq,
|
| 843 |
+
input_ids=input_ids,
|
| 844 |
+
**kwargs,
|
| 845 |
+
)
|
| 846 |
+
if len(metrics) > 0:
|
| 847 |
+
step_metrics.append(metrics)
|
| 848 |
+
if metric is not None and (best_metric is None or metric > best_metric):
|
| 849 |
+
best_metric = metric
|
| 850 |
+
best_step = step
|
| 851 |
+
best_state = self._ttt_snapshot_lora_state()
|
| 852 |
+
|
| 853 |
+
if cfg.automatic_best_state_reset and best_state is not None:
|
| 854 |
+
self._ttt_restore_lora_state(best_state)
|
| 855 |
+
finally:
|
| 856 |
+
for param, value in requires_grad.items():
|
| 857 |
+
param.requires_grad_(value)
|
| 858 |
+
for module, training in module_modes.items():
|
| 859 |
+
module.train(training)
|
| 860 |
+
|
| 861 |
+
return {
|
| 862 |
+
"losses": losses,
|
| 863 |
+
"step_metrics": step_metrics,
|
| 864 |
+
"best_step": best_step,
|
| 865 |
+
"best_metric": best_metric,
|
| 866 |
+
}
|
fastplms/registry.py
ADDED
|
@@ -0,0 +1,1486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ers. Tooling can
|
| 4 |
+
therefore inspect supported checkpoints, licenses, and reference sources without
|
| 5 |
+
initializing a model runtime or downloading any files.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
import tomllib
|
| 12 |
+
from collections.abc import Iterator, Mapping
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from importlib import resources
|
| 16 |
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
| 17 |
+
from types import MappingProxyType
|
| 18 |
+
from typing import Any, Literal, cast
|
| 19 |
+
from urllib.parse import urlparse
|
| 20 |
+
|
| 21 |
+
_HEX_RE = re.compile(r"^[0-9a-f]+$")
|
| 22 |
+
_IDENTIFIER_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
|
| 23 |
+
_HUB_LICENSE_NAME_RE = re.compile(r"[^a-z0-9.]+")
|
| 24 |
+
_WINDOWS_INVALID_PATH_CHARACTERS = frozenset('<>:"|?*')
|
| 25 |
+
_WINDOWS_RESERVED_PATH_NAMES = frozenset(
|
| 26 |
+
{"AUX", "CON", "NUL", "PRN"}
|
| 27 |
+
| {f"COM{index}" for index in range(1, 10)}
|
| 28 |
+
| {f"LPT{index}" for index in range(1, 10)}
|
| 29 |
+
)
|
| 30 |
+
_REPOSITORY_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*$")
|
| 31 |
+
_REFERENCE_CONTAINER_RE = re.compile(r"^reference-[a-z0-9]+(?:-[a-z0-9]+)*$")
|
| 32 |
+
_REFERENCE_ADAPTER_RE = re.compile(
|
| 33 |
+
r"^tests\.parity\.support\.reference_adapters\.[a-z_][a-z0-9_]*$"
|
| 34 |
+
)
|
| 35 |
+
_DOCUMENTATION_FRAGMENT_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
| 36 |
+
_ALLOWED_ATTENTION = frozenset(
|
| 37 |
+
{"eager", "sdpa", "flex_attention", "flash_attention_2", "flash_attention_3"}
|
| 38 |
+
)
|
| 39 |
+
_ALLOWED_DTYPES = frozenset({"float32", "bfloat16"})
|
| 40 |
+
_ALLOWED_PRECISIONS = frozenset({"default", "auto", "fp32", "bf16", "fp8"})
|
| 41 |
+
_ALLOWED_BF16_EXECUTIONS = frozenset({"static_parameters", "fp32_parameters_autocast"})
|
| 42 |
+
HUB_LICENSE_IDENTIFIERS = frozenset({"mit", "apache-2.0", "cc-by-nc-sa-4.0", "other"})
|
| 43 |
+
_ALLOWED_TOKENIZER_MODES = frozenset({"tokenizer", "sequence", "structure"})
|
| 44 |
+
_ALLOWED_SIZE_CATEGORIES = frozenset({"small", "medium", "large", "xlarge", "structure"})
|
| 45 |
+
RuntimeExtra = Literal["core", "structure"]
|
| 46 |
+
TestTier = Literal["check", "compliance", "structure", "feature", "artifact", "benchmark"]
|
| 47 |
+
VramTier = Literal["sequence", "large-sequence", "structure", "structure-6b"]
|
| 48 |
+
GenerationContract = Literal["not_applicable", "required", "official_unavailable"]
|
| 49 |
+
RuntimeAssetTrustKind = Literal["hash_pinned_pickle"]
|
| 50 |
+
Bf16Execution = Literal["static_parameters", "fp32_parameters_autocast"]
|
| 51 |
+
DtypeName = Literal["float32", "bfloat16"]
|
| 52 |
+
_ALLOWED_EXTRAS = frozenset({"core", "structure"})
|
| 53 |
+
_ALLOWED_TEST_TIERS = frozenset(
|
| 54 |
+
{"check", "compliance", "structure", "feature", "artifact", "benchmark"}
|
| 55 |
+
)
|
| 56 |
+
_ALLOWED_VRAM_TIERS = frozenset({"sequence", "large-sequence", "structure", "structure-6b"})
|
| 57 |
+
_ALLOWED_GENERATION_CONTRACTS = frozenset({"not_applicable", "required", "official_unavailable"})
|
| 58 |
+
_ALLOWED_RUNTIME_ASSET_TRUST_KINDS = frozenset({"hash_pinned_pickle"})
|
| 59 |
+
_ALLOWED_RUNTIME_ASSET_OFFLINE_BEHAVIORS = frozenset({"requires_cached_verified_file"})
|
| 60 |
+
_ALLOWED_AUTO_CLASSES = frozenset(
|
| 61 |
+
{
|
| 62 |
+
"AutoConfig",
|
| 63 |
+
"AutoModel",
|
| 64 |
+
"AutoModelForMaskedLM",
|
| 65 |
+
"AutoModelForProteinFolding",
|
| 66 |
+
"AutoModelForSequenceClassification",
|
| 67 |
+
"AutoModelForSeq2SeqLM",
|
| 68 |
+
"AutoModelForTokenClassification",
|
| 69 |
+
}
|
| 70 |
+
)
|
| 71 |
+
_WEIGHT_SUFFIXES = (".bin", ".ckpt", ".pt", ".pth", ".safetensors")
|
| 72 |
+
_ALLOWED_ORACLE_ASSET_ROLES = frozenset({"weights", "contact_regression"})
|
| 73 |
+
_FAIR_ESM_ASSET_HOST = "dl.fbaipublicfiles.com"
|
| 74 |
+
_ROOT_FIELDS = frozenset(
|
| 75 |
+
{
|
| 76 |
+
"schema_version",
|
| 77 |
+
"legal_files",
|
| 78 |
+
"attention_kernels",
|
| 79 |
+
"upstreams",
|
| 80 |
+
"families",
|
| 81 |
+
"models",
|
| 82 |
+
"runtime_assets",
|
| 83 |
+
}
|
| 84 |
+
)
|
| 85 |
+
_UPSTREAM_FIELDS = frozenset(
|
| 86 |
+
{
|
| 87 |
+
"id",
|
| 88 |
+
"path",
|
| 89 |
+
"url",
|
| 90 |
+
"revision",
|
| 91 |
+
"license",
|
| 92 |
+
"license_files",
|
| 93 |
+
"license_digests",
|
| 94 |
+
"distribution_files",
|
| 95 |
+
}
|
| 96 |
+
)
|
| 97 |
+
_FAMILY_FIELDS = frozenset(
|
| 98 |
+
{
|
| 99 |
+
"architecture",
|
| 100 |
+
"upstreams",
|
| 101 |
+
"tokenizer_mode",
|
| 102 |
+
"public_input",
|
| 103 |
+
"extra",
|
| 104 |
+
"reference_container",
|
| 105 |
+
"reference_adapter",
|
| 106 |
+
"attention",
|
| 107 |
+
"dtypes",
|
| 108 |
+
"bf16_execution",
|
| 109 |
+
"precisions",
|
| 110 |
+
"experimental_precisions",
|
| 111 |
+
"vram_tier",
|
| 112 |
+
"checkpoint_license",
|
| 113 |
+
"hub_license",
|
| 114 |
+
"hub_license_name",
|
| 115 |
+
"hub_license_link",
|
| 116 |
+
"state_transform",
|
| 117 |
+
"conversion_provenance",
|
| 118 |
+
"representative",
|
| 119 |
+
"documentation",
|
| 120 |
+
"test_tiers",
|
| 121 |
+
"runtime_paths",
|
| 122 |
+
"requires_complete_weight_publication",
|
| 123 |
+
"weights_publication_allowed",
|
| 124 |
+
"auto_map",
|
| 125 |
+
"tokenizer_class",
|
| 126 |
+
"backbone_model",
|
| 127 |
+
}
|
| 128 |
+
)
|
| 129 |
+
_MODEL_FIELDS = frozenset(
|
| 130 |
+
{
|
| 131 |
+
"id",
|
| 132 |
+
"family",
|
| 133 |
+
"size_category",
|
| 134 |
+
"generation_contract",
|
| 135 |
+
"fast_repo",
|
| 136 |
+
"fast_revision",
|
| 137 |
+
"fast_files",
|
| 138 |
+
"fast_unresolved_files",
|
| 139 |
+
"official_repo",
|
| 140 |
+
"official_revision",
|
| 141 |
+
"official_files",
|
| 142 |
+
"official_unresolved_files",
|
| 143 |
+
"oracle_assets",
|
| 144 |
+
"official_golden",
|
| 145 |
+
"artifact_source",
|
| 146 |
+
"canonical_state_sha256",
|
| 147 |
+
"tokenizer_source",
|
| 148 |
+
"auto_map",
|
| 149 |
+
"notes",
|
| 150 |
+
"msa_conditioning",
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
_RUNTIME_ASSET_FIELDS = frozenset(
|
| 154 |
+
{
|
| 155 |
+
"id",
|
| 156 |
+
"repository",
|
| 157 |
+
"revision",
|
| 158 |
+
"path",
|
| 159 |
+
"sha256",
|
| 160 |
+
"size",
|
| 161 |
+
"consumer_family",
|
| 162 |
+
"trust_kind",
|
| 163 |
+
"license",
|
| 164 |
+
"offline_behavior",
|
| 165 |
+
}
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class RegistryError(ValueError):
|
| 170 |
+
"""Raised when the model manifest is incomplete or internally inconsistent."""
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _portable_relative_path(value: str, context: str) -> PurePosixPath:
|
| 174 |
+
"""Return one normalized cross-platform relative path or fail closed."""
|
| 175 |
+
|
| 176 |
+
posix = PurePosixPath(value)
|
| 177 |
+
windows = PureWindowsPath(value)
|
| 178 |
+
unsafe_windows_part = any(
|
| 179 |
+
part.rstrip(" .") != part
|
| 180 |
+
or part.split(".", maxsplit=1)[0].upper() in _WINDOWS_RESERVED_PATH_NAMES
|
| 181 |
+
or any(
|
| 182 |
+
ord(character) < 32 or character in _WINDOWS_INVALID_PATH_CHARACTERS
|
| 183 |
+
for character in part
|
| 184 |
+
)
|
| 185 |
+
for part in posix.parts
|
| 186 |
+
)
|
| 187 |
+
if (
|
| 188 |
+
not value
|
| 189 |
+
or not posix.parts
|
| 190 |
+
or posix == PurePosixPath(".")
|
| 191 |
+
or posix.is_absolute()
|
| 192 |
+
or windows.is_absolute()
|
| 193 |
+
or windows.drive
|
| 194 |
+
or "\\" in value
|
| 195 |
+
or "." in posix.parts
|
| 196 |
+
or ".." in posix.parts
|
| 197 |
+
or value != posix.as_posix()
|
| 198 |
+
or any(
|
| 199 |
+
part.lower() in {".git", ".cache", "__pycache__"}
|
| 200 |
+
for part in posix.parts
|
| 201 |
+
)
|
| 202 |
+
or unsafe_windows_part
|
| 203 |
+
):
|
| 204 |
+
raise RegistryError(f"{context} is not portable: {value!r}")
|
| 205 |
+
return posix
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@dataclass(frozen=True, slots=True)
|
| 209 |
+
class FileDigest:
|
| 210 |
+
"""Expected content identity for one pinned file."""
|
| 211 |
+
|
| 212 |
+
path: str
|
| 213 |
+
algorithm: str
|
| 214 |
+
digest: str
|
| 215 |
+
|
| 216 |
+
@classmethod
|
| 217 |
+
def parse(cls, value: str) -> FileDigest:
|
| 218 |
+
try:
|
| 219 |
+
path, encoded_digest = value.split("=", maxsplit=1)
|
| 220 |
+
algorithm, digest = encoded_digest.split(":", maxsplit=1)
|
| 221 |
+
except ValueError as error:
|
| 222 |
+
raise RegistryError("File digests must use '<path>=<algorithm>:<digest>'.") from error
|
| 223 |
+
|
| 224 |
+
_portable_relative_path(path, "Checkpoint file path")
|
| 225 |
+
|
| 226 |
+
expected_length = {"git-sha1": 40, "sha256": 64}.get(algorithm)
|
| 227 |
+
if expected_length is None:
|
| 228 |
+
raise RegistryError(f"Unsupported file digest algorithm: {algorithm!r}")
|
| 229 |
+
if len(digest) != expected_length or _HEX_RE.fullmatch(digest) is None:
|
| 230 |
+
raise RegistryError(f"Invalid {algorithm} digest for {path!r}: {digest!r}")
|
| 231 |
+
return cls(path=path, algorithm=algorithm, digest=digest)
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def encoded(self) -> str:
|
| 235 |
+
return f"{self.algorithm}:{self.digest}"
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@dataclass(frozen=True, slots=True)
|
| 239 |
+
class CheckpointSource:
|
| 240 |
+
"""One immutable Hugging Face repository snapshot."""
|
| 241 |
+
|
| 242 |
+
repo_id: str
|
| 243 |
+
revision: str
|
| 244 |
+
files: tuple[FileDigest, ...]
|
| 245 |
+
unresolved_files: tuple[str, ...] = ()
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def file_map(self) -> Mapping[str, FileDigest]:
|
| 249 |
+
return MappingProxyType({item.path: item for item in self.files})
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@dataclass(frozen=True, slots=True)
|
| 253 |
+
class OracleAsset:
|
| 254 |
+
"""Hash-pinned external file required by a native parity oracle."""
|
| 255 |
+
|
| 256 |
+
role: str
|
| 257 |
+
path: str
|
| 258 |
+
url: str
|
| 259 |
+
sha256: str
|
| 260 |
+
size: int
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@dataclass(frozen=True, slots=True)
|
| 264 |
+
class RuntimeAsset:
|
| 265 |
+
"""Immutable runtime data with an explicit deserialization trust boundary."""
|
| 266 |
+
|
| 267 |
+
id: str
|
| 268 |
+
repository: str
|
| 269 |
+
revision: str
|
| 270 |
+
path: str
|
| 271 |
+
sha256: str
|
| 272 |
+
size: int
|
| 273 |
+
consumer_family: str
|
| 274 |
+
trust_kind: RuntimeAssetTrustKind
|
| 275 |
+
license_expression: str
|
| 276 |
+
offline_behavior: str
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@dataclass(frozen=True, slots=True)
|
| 280 |
+
class OfficialGolden:
|
| 281 |
+
"""Hash-pinned official output bundle required by the check tier."""
|
| 282 |
+
|
| 283 |
+
metadata: FileDigest
|
| 284 |
+
tensors: FileDigest
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@dataclass(frozen=True, slots=True)
|
| 288 |
+
class UpstreamSource:
|
| 289 |
+
"""Pinned official implementation used as a parity oracle."""
|
| 290 |
+
|
| 291 |
+
id: str
|
| 292 |
+
path: str
|
| 293 |
+
url: str
|
| 294 |
+
revision: str
|
| 295 |
+
license_expression: str
|
| 296 |
+
license_files: tuple[str, ...]
|
| 297 |
+
license_digests: tuple[FileDigest, ...] = ()
|
| 298 |
+
distribution_files: tuple[FileDigest, ...] = ()
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@dataclass(frozen=True, slots=True)
|
| 302 |
+
class AttentionKernelSpec:
|
| 303 |
+
"""Immutable Hugging Face kernel used by one attention backend."""
|
| 304 |
+
|
| 305 |
+
implementation: str
|
| 306 |
+
repository: str
|
| 307 |
+
revision: str
|
| 308 |
+
version: int
|
| 309 |
+
expected_variant: str
|
| 310 |
+
dtypes: tuple[DtypeName, ...]
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@dataclass(frozen=True, slots=True)
|
| 314 |
+
class ModelFamily:
|
| 315 |
+
"""Shared runtime and compliance contract for one architecture family."""
|
| 316 |
+
|
| 317 |
+
id: str
|
| 318 |
+
architecture: str
|
| 319 |
+
upstreams: tuple[str, ...]
|
| 320 |
+
tokenizer_mode: str
|
| 321 |
+
public_input: str
|
| 322 |
+
extra: RuntimeExtra
|
| 323 |
+
reference_container: str
|
| 324 |
+
reference_adapter: str
|
| 325 |
+
attention: tuple[str, ...]
|
| 326 |
+
dtypes: tuple[DtypeName, ...]
|
| 327 |
+
bf16_execution: Bf16Execution
|
| 328 |
+
precisions: tuple[str, ...]
|
| 329 |
+
vram_tier: VramTier
|
| 330 |
+
checkpoint_license: str
|
| 331 |
+
hub_license: str
|
| 332 |
+
state_transform: str
|
| 333 |
+
representative: str
|
| 334 |
+
documentation: str
|
| 335 |
+
test_tiers: tuple[TestTier, ...]
|
| 336 |
+
runtime_paths: tuple[str, ...]
|
| 337 |
+
auto_map_items: tuple[tuple[str, str], ...]
|
| 338 |
+
requires_complete_weight_publication: bool = False
|
| 339 |
+
weights_publication_allowed: bool = False
|
| 340 |
+
experimental_precisions: tuple[str, ...] = ()
|
| 341 |
+
tokenizer_class: str | None = None
|
| 342 |
+
hub_license_name: str | None = None
|
| 343 |
+
hub_license_link: str | None = None
|
| 344 |
+
conversion_provenance: str = ""
|
| 345 |
+
backbone_model: str | None = None
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def auto_map(self) -> Mapping[str, str]:
|
| 349 |
+
return MappingProxyType(dict(self.auto_map_items))
|
| 350 |
+
|
| 351 |
+
@property
|
| 352 |
+
def hub_license_metadata(self) -> Mapping[str, str]:
|
| 353 |
+
"""Return valid Hugging Face model-card license fields."""
|
| 354 |
+
|
| 355 |
+
metadata = {"license": self.hub_license}
|
| 356 |
+
if self.hub_license_name is not None:
|
| 357 |
+
# Hugging Face validates custom license names as lowercase slugs,
|
| 358 |
+
# while the manifest retains the reader-facing display name used
|
| 359 |
+
# in generated prose.
|
| 360 |
+
metadata["license_name"] = _HUB_LICENSE_NAME_RE.sub(
|
| 361 |
+
"-",
|
| 362 |
+
self.hub_license_name.lower(),
|
| 363 |
+
).strip("-.")
|
| 364 |
+
if self.hub_license_link is not None:
|
| 365 |
+
metadata["license_link"] = self.hub_license_link
|
| 366 |
+
return MappingProxyType(metadata)
|
| 367 |
+
|
| 368 |
+
@property
|
| 369 |
+
def stable_precisions(self) -> tuple[str, ...]:
|
| 370 |
+
"""Return precision policies covered by the release contract."""
|
| 371 |
+
|
| 372 |
+
experimental = set(self.experimental_precisions)
|
| 373 |
+
return tuple(precision for precision in self.precisions if precision not in experimental)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@dataclass(frozen=True, slots=True)
|
| 377 |
+
class ModelSpec:
|
| 378 |
+
"""Complete immutable source and runtime contract for one checkpoint."""
|
| 379 |
+
|
| 380 |
+
id: str
|
| 381 |
+
family: ModelFamily
|
| 382 |
+
fast: CheckpointSource
|
| 383 |
+
official: CheckpointSource
|
| 384 |
+
size_category: str
|
| 385 |
+
generation_contract: GenerationContract = "not_applicable"
|
| 386 |
+
oracle_assets: tuple[OracleAsset, ...] = ()
|
| 387 |
+
official_golden: OfficialGolden | None = None
|
| 388 |
+
artifact_source: str = "fast"
|
| 389 |
+
canonical_state_sha256: str | None = None
|
| 390 |
+
tokenizer_source_id: str | None = None
|
| 391 |
+
auto_map_items: tuple[tuple[str, str], ...] = ()
|
| 392 |
+
notes: str = ""
|
| 393 |
+
msa_conditioning: bool | None = None
|
| 394 |
+
|
| 395 |
+
@property
|
| 396 |
+
def is_deep_reference(self) -> bool:
|
| 397 |
+
return self.id == self.family.representative
|
| 398 |
+
|
| 399 |
+
@property
|
| 400 |
+
def auto_map(self) -> Mapping[str, str]:
|
| 401 |
+
if self.auto_map_items:
|
| 402 |
+
return MappingProxyType(dict(self.auto_map_items))
|
| 403 |
+
return self.family.auto_map
|
| 404 |
+
|
| 405 |
+
@property
|
| 406 |
+
def artifact_checkpoint(self) -> CheckpointSource:
|
| 407 |
+
"""Return the checkpoint selected for local artifact construction."""
|
| 408 |
+
|
| 409 |
+
return self.fast if self.artifact_source == "fast" else self.official
|
| 410 |
+
|
| 411 |
+
@property
|
| 412 |
+
def oracle_asset_map(self) -> Mapping[str, OracleAsset]:
|
| 413 |
+
"""Return native oracle assets keyed by their declared role."""
|
| 414 |
+
|
| 415 |
+
return MappingProxyType({asset.role: asset for asset in self.oracle_assets})
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class ModelRegistry(Mapping[str, ModelSpec]):
|
| 419 |
+
"""Validated mapping of model IDs to typed model specifications."""
|
| 420 |
+
|
| 421 |
+
def __init__(
|
| 422 |
+
self,
|
| 423 |
+
*,
|
| 424 |
+
schema_version: int,
|
| 425 |
+
upstreams: Mapping[str, UpstreamSource],
|
| 426 |
+
families: Mapping[str, ModelFamily],
|
| 427 |
+
models: Mapping[str, ModelSpec],
|
| 428 |
+
runtime_assets: Mapping[str, RuntimeAsset] = MappingProxyType({}),
|
| 429 |
+
attention_kernels: Mapping[str, AttentionKernelSpec] = MappingProxyType({}),
|
| 430 |
+
legal_files: tuple[FileDigest, ...] = (),
|
| 431 |
+
) -> None:
|
| 432 |
+
self.schema_version = schema_version
|
| 433 |
+
self.upstreams = MappingProxyType(dict(upstreams))
|
| 434 |
+
self.attention_kernels = MappingProxyType(dict(attention_kernels))
|
| 435 |
+
self.families = MappingProxyType(dict(families))
|
| 436 |
+
self._models = MappingProxyType(dict(models))
|
| 437 |
+
self.runtime_assets = MappingProxyType(dict(runtime_assets))
|
| 438 |
+
self.legal_files = legal_files
|
| 439 |
+
|
| 440 |
+
def __getitem__(self, key: str) -> ModelSpec:
|
| 441 |
+
return self._models[key]
|
| 442 |
+
|
| 443 |
+
def __iter__(self) -> Iterator[str]:
|
| 444 |
+
return iter(self._models)
|
| 445 |
+
|
| 446 |
+
def __len__(self) -> int:
|
| 447 |
+
return len(self._models)
|
| 448 |
+
|
| 449 |
+
def by_family(self, family_id: str) -> tuple[ModelSpec, ...]:
|
| 450 |
+
if family_id not in self.families:
|
| 451 |
+
raise KeyError(family_id)
|
| 452 |
+
return tuple(model for model in self._models.values() if model.family.id == family_id)
|
| 453 |
+
|
| 454 |
+
def supported_attention_dtypes(
|
| 455 |
+
self,
|
| 456 |
+
family_id: str,
|
| 457 |
+
implementation: str,
|
| 458 |
+
) -> tuple[DtypeName, ...]:
|
| 459 |
+
"""Return manifest-supported dtypes for one family/backend pair."""
|
| 460 |
+
|
| 461 |
+
family = self.families[family_id]
|
| 462 |
+
if implementation not in family.attention:
|
| 463 |
+
raise KeyError(
|
| 464 |
+
f"Family {family_id!r} does not advertise attention backend "
|
| 465 |
+
f"{implementation!r}."
|
| 466 |
+
)
|
| 467 |
+
kernel = self.attention_kernels.get(implementation)
|
| 468 |
+
if kernel is None:
|
| 469 |
+
return family.dtypes
|
| 470 |
+
return tuple(dtype for dtype in family.dtypes if dtype in kernel.dtypes)
|
| 471 |
+
|
| 472 |
+
def require_resolved(self, model_id: str | None = None) -> None:
|
| 473 |
+
"""Fail release validation when required file identities remain unresolved."""
|
| 474 |
+
|
| 475 |
+
selected = self._models.values() if model_id is None else (self._models[model_id],)
|
| 476 |
+
unresolved: list[str] = []
|
| 477 |
+
for model in selected:
|
| 478 |
+
for label, checkpoint in (("fast", model.fast), ("official", model.official)):
|
| 479 |
+
for path in checkpoint.unresolved_files:
|
| 480 |
+
unresolved.append(f"{model.id}.{label}:{path}")
|
| 481 |
+
if unresolved:
|
| 482 |
+
detail = ", ".join(unresolved)
|
| 483 |
+
raise RegistryError(f"Release provenance is unresolved: {detail}")
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _reject_unknown_fields(
|
| 487 |
+
table: Mapping[str, Any],
|
| 488 |
+
allowed: frozenset[str],
|
| 489 |
+
context: str,
|
| 490 |
+
) -> None:
|
| 491 |
+
unknown = sorted(set(table).difference(allowed))
|
| 492 |
+
if unknown:
|
| 493 |
+
raise RegistryError(f"{context} contains unknown fields: {unknown}.")
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def _require_str(table: Mapping[str, Any], key: str, context: str) -> str:
|
| 497 |
+
value = table.get(key)
|
| 498 |
+
if not isinstance(value, str) or not value.strip():
|
| 499 |
+
raise RegistryError(f"{context}.{key} must be a non-empty string.")
|
| 500 |
+
return value
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _require_enum(
|
| 504 |
+
table: Mapping[str, Any],
|
| 505 |
+
key: str,
|
| 506 |
+
context: str,
|
| 507 |
+
allowed: frozenset[str],
|
| 508 |
+
) -> str:
|
| 509 |
+
value = _require_str(table, key, context)
|
| 510 |
+
if value not in allowed:
|
| 511 |
+
raise RegistryError(
|
| 512 |
+
f"{context}.{key} must be one of {sorted(allowed)}; received {value!r}."
|
| 513 |
+
)
|
| 514 |
+
return value
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def _parse_reference_container(table: Mapping[str, Any], context: str) -> str:
|
| 518 |
+
value = _require_str(table, "reference_container", context)
|
| 519 |
+
if _REFERENCE_CONTAINER_RE.fullmatch(value) is None:
|
| 520 |
+
raise RegistryError(
|
| 521 |
+
f"{context}.reference_container must be a portable 'reference-<name>' target."
|
| 522 |
+
)
|
| 523 |
+
return value
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _parse_reference_adapter(table: Mapping[str, Any], context: str) -> str:
|
| 527 |
+
value = _require_str(table, "reference_adapter", context)
|
| 528 |
+
if _REFERENCE_ADAPTER_RE.fullmatch(value) is None:
|
| 529 |
+
raise RegistryError(
|
| 530 |
+
f"{context}.reference_adapter must name one module under "
|
| 531 |
+
"tests.parity.support.reference_adapters."
|
| 532 |
+
)
|
| 533 |
+
return value
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _parse_documentation_path(table: Mapping[str, Any], context: str) -> str:
|
| 537 |
+
value = _require_str(table, "documentation", context)
|
| 538 |
+
if value.count("#") > 1 or "\\" in value:
|
| 539 |
+
raise RegistryError(f"{context}.documentation must be a portable documentation path.")
|
| 540 |
+
raw_path, separator, fragment = value.partition("#")
|
| 541 |
+
path = PurePosixPath(raw_path)
|
| 542 |
+
if (
|
| 543 |
+
path.is_absolute()
|
| 544 |
+
or ".." in path.parts
|
| 545 |
+
or len(path.parts) < 2
|
| 546 |
+
or path.parts[0] != "docs"
|
| 547 |
+
or path.suffix != ".md"
|
| 548 |
+
or path.as_posix() != raw_path
|
| 549 |
+
):
|
| 550 |
+
raise RegistryError(
|
| 551 |
+
f"{context}.documentation must reference a normalized Markdown file under docs/."
|
| 552 |
+
)
|
| 553 |
+
if separator and _DOCUMENTATION_FRAGMENT_RE.fullmatch(fragment) is None:
|
| 554 |
+
raise RegistryError(f"{context}.documentation has an invalid heading fragment.")
|
| 555 |
+
return value
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def _require_str_list(table: Mapping[str, Any], key: str, context: str) -> tuple[str, ...]:
|
| 559 |
+
value = table.get(key)
|
| 560 |
+
if not isinstance(value, list) or not value or any(not isinstance(item, str) for item in value):
|
| 561 |
+
raise RegistryError(f"{context}.{key} must be a non-empty string array.")
|
| 562 |
+
result = tuple(value)
|
| 563 |
+
if len(set(result)) != len(result):
|
| 564 |
+
raise RegistryError(f"{context}.{key} contains duplicate values.")
|
| 565 |
+
return result
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _optional_str_list(table: Mapping[str, Any], key: str, context: str) -> tuple[str, ...]:
|
| 569 |
+
value = table.get(key, [])
|
| 570 |
+
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
| 571 |
+
raise RegistryError(f"{context}.{key} must be a string array.")
|
| 572 |
+
result = tuple(value)
|
| 573 |
+
if len(set(result)) != len(result):
|
| 574 |
+
raise RegistryError(f"{context}.{key} contains duplicate values.")
|
| 575 |
+
return result
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _optional_str(table: Mapping[str, Any], key: str, context: str) -> str | None:
|
| 579 |
+
value = table.get(key)
|
| 580 |
+
if value is None:
|
| 581 |
+
return None
|
| 582 |
+
if (
|
| 583 |
+
not isinstance(value, str)
|
| 584 |
+
or not value.strip()
|
| 585 |
+
or value != value.strip()
|
| 586 |
+
or "\n" in value
|
| 587 |
+
or "\r" in value
|
| 588 |
+
):
|
| 589 |
+
raise RegistryError(f"{context}.{key} must be a non-empty single-line string.")
|
| 590 |
+
return value
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _parse_hub_license(
|
| 594 |
+
table: Mapping[str, Any],
|
| 595 |
+
*,
|
| 596 |
+
checkpoint_license: str,
|
| 597 |
+
context: str,
|
| 598 |
+
) -> tuple[str, str | None, str | None]:
|
| 599 |
+
expected_fields = {"hub_license", "hub_license_name", "hub_license_link"}
|
| 600 |
+
unknown_fields = sorted(
|
| 601 |
+
key for key in table if key.startswith("hub_") and key not in expected_fields
|
| 602 |
+
)
|
| 603 |
+
if unknown_fields:
|
| 604 |
+
raise RegistryError(f"{context} contains unsupported Hub license fields: {unknown_fields}.")
|
| 605 |
+
identifier = _require_str(table, "hub_license", context)
|
| 606 |
+
if identifier not in HUB_LICENSE_IDENTIFIERS:
|
| 607 |
+
raise RegistryError(
|
| 608 |
+
f"{context}.hub_license must be a supported Hugging Face license identifier."
|
| 609 |
+
)
|
| 610 |
+
expected_identifier: str | None = None
|
| 611 |
+
for prefix, candidate in (
|
| 612 |
+
("MIT", "mit"),
|
| 613 |
+
("Apache-2.0", "apache-2.0"),
|
| 614 |
+
("CC-BY-NC-SA-4.0", "cc-by-nc-sa-4.0"),
|
| 615 |
+
("Profluent-E1-Agreement", "other"),
|
| 616 |
+
("Unresolved", "other"),
|
| 617 |
+
):
|
| 618 |
+
if checkpoint_license.startswith(prefix):
|
| 619 |
+
expected_identifier = candidate
|
| 620 |
+
break
|
| 621 |
+
if expected_identifier is None:
|
| 622 |
+
raise RegistryError(
|
| 623 |
+
f"{context}.checkpoint_license has no declared Hugging Face identifier mapping."
|
| 624 |
+
)
|
| 625 |
+
if identifier != expected_identifier:
|
| 626 |
+
raise RegistryError(
|
| 627 |
+
f"{context}.hub_license must be {expected_identifier!r} for "
|
| 628 |
+
f"checkpoint terms {checkpoint_license!r}."
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
name = _optional_str(table, "hub_license_name", context)
|
| 632 |
+
link = _optional_str(table, "hub_license_link", context)
|
| 633 |
+
if identifier != "other":
|
| 634 |
+
if name is not None or link is not None:
|
| 635 |
+
raise RegistryError(
|
| 636 |
+
f"{context} may define hub_license_name and hub_license_link only "
|
| 637 |
+
"when hub_license='other'."
|
| 638 |
+
)
|
| 639 |
+
return identifier, None, None
|
| 640 |
+
if name is None or link is None:
|
| 641 |
+
raise RegistryError(
|
| 642 |
+
f"{context} must define hub_license_name and hub_license_link when hub_license='other'."
|
| 643 |
+
)
|
| 644 |
+
parsed_link = urlparse(link)
|
| 645 |
+
if (
|
| 646 |
+
parsed_link.scheme != "https"
|
| 647 |
+
or not parsed_link.netloc
|
| 648 |
+
or not parsed_link.path
|
| 649 |
+
or parsed_link.username is not None
|
| 650 |
+
or parsed_link.password is not None
|
| 651 |
+
):
|
| 652 |
+
raise RegistryError(f"{context}.hub_license_link must be an absolute HTTPS URL.")
|
| 653 |
+
return identifier, name, link
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def _require_digest_list(
|
| 657 |
+
table: Mapping[str, Any], key: str, context: str
|
| 658 |
+
) -> tuple[FileDigest, ...]:
|
| 659 |
+
encoded = _require_str_list(table, key, context)
|
| 660 |
+
result = tuple(FileDigest.parse(value) for value in encoded)
|
| 661 |
+
paths = [item.path for item in result]
|
| 662 |
+
if len(paths) != len(set(paths)):
|
| 663 |
+
raise RegistryError(f"{context}.{key} contains duplicate paths.")
|
| 664 |
+
return result
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def _validate_revision(revision: str, context: str) -> None:
|
| 668 |
+
if len(revision) != 40 or _HEX_RE.fullmatch(revision) is None:
|
| 669 |
+
raise RegistryError(f"{context} must be an immutable 40-character commit revision.")
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def _parse_checkpoint(table: Mapping[str, Any], prefix: str, context: str) -> CheckpointSource:
|
| 673 |
+
repo_id = _require_str(table, f"{prefix}_repo", context)
|
| 674 |
+
if _REPOSITORY_ID_RE.fullmatch(repo_id) is None:
|
| 675 |
+
raise RegistryError(f"{context}.{prefix}_repo must be a Hugging Face repository ID.")
|
| 676 |
+
revision = _require_str(table, f"{prefix}_revision", context)
|
| 677 |
+
_validate_revision(revision, f"{context}.{prefix}_revision")
|
| 678 |
+
encoded_files = _require_str_list(table, f"{prefix}_files", context)
|
| 679 |
+
files = tuple(FileDigest.parse(value) for value in encoded_files)
|
| 680 |
+
paths = [item.path for item in files]
|
| 681 |
+
if len(paths) != len(set(paths)):
|
| 682 |
+
raise RegistryError(f"{context}.{prefix}_files contains duplicate paths.")
|
| 683 |
+
if not any(item.path.endswith(_WEIGHT_SUFFIXES) for item in files):
|
| 684 |
+
raise RegistryError(f"{context}.{prefix}_files does not identify a weight file.")
|
| 685 |
+
unresolved_files = _optional_str_list(table, f"{prefix}_unresolved_files", context)
|
| 686 |
+
for unresolved_path in unresolved_files:
|
| 687 |
+
_portable_relative_path(unresolved_path, "Unresolved checkpoint path")
|
| 688 |
+
if unresolved_path in paths:
|
| 689 |
+
raise RegistryError(
|
| 690 |
+
f"{context}.{prefix} marks {unresolved_path!r} both resolved and unresolved."
|
| 691 |
+
)
|
| 692 |
+
return CheckpointSource(
|
| 693 |
+
repo_id=repo_id,
|
| 694 |
+
revision=revision,
|
| 695 |
+
files=files,
|
| 696 |
+
unresolved_files=unresolved_files,
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def _parse_oracle_assets(table: Mapping[str, Any], context: str) -> tuple[OracleAsset, ...]:
|
| 701 |
+
raw = table.get("oracle_assets", [])
|
| 702 |
+
if not isinstance(raw, list):
|
| 703 |
+
raise RegistryError(f"{context}.oracle_assets must be an array of tables.")
|
| 704 |
+
result: list[OracleAsset] = []
|
| 705 |
+
for index, value in enumerate(raw):
|
| 706 |
+
asset_context = f"{context}.oracle_assets[{index}]"
|
| 707 |
+
if not isinstance(value, dict):
|
| 708 |
+
raise RegistryError(f"{asset_context} must be a table.")
|
| 709 |
+
expected_fields = {"role", "path", "url", "sha256", "size"}
|
| 710 |
+
if set(value) != expected_fields:
|
| 711 |
+
raise RegistryError(f"{asset_context} must contain exactly {sorted(expected_fields)}.")
|
| 712 |
+
role = _require_str(value, "role", asset_context)
|
| 713 |
+
if role not in _ALLOWED_ORACLE_ASSET_ROLES:
|
| 714 |
+
raise RegistryError(f"Unsupported oracle asset role: {role!r}.")
|
| 715 |
+
path = _require_str(value, "path", asset_context)
|
| 716 |
+
try:
|
| 717 |
+
normalized_path = _portable_relative_path(path, "Oracle asset path")
|
| 718 |
+
except RegistryError as error:
|
| 719 |
+
raise RegistryError(f"Invalid oracle asset path: {path!r}.") from error
|
| 720 |
+
if normalized_path.suffix != ".pt":
|
| 721 |
+
raise RegistryError(f"Invalid oracle asset path: {path!r}.")
|
| 722 |
+
url = _require_str(value, "url", asset_context)
|
| 723 |
+
parsed_url = urlparse(url)
|
| 724 |
+
if (
|
| 725 |
+
parsed_url.scheme != "https"
|
| 726 |
+
or parsed_url.hostname != _FAIR_ESM_ASSET_HOST
|
| 727 |
+
or parsed_url.path != f"/fair-esm/{path}"
|
| 728 |
+
or parsed_url.params
|
| 729 |
+
or parsed_url.query
|
| 730 |
+
or parsed_url.fragment
|
| 731 |
+
):
|
| 732 |
+
raise RegistryError(f"Invalid fair-esm oracle asset URL: {url!r}.")
|
| 733 |
+
sha256 = _require_str(value, "sha256", asset_context)
|
| 734 |
+
if len(sha256) != 64 or _HEX_RE.fullmatch(sha256) is None:
|
| 735 |
+
raise RegistryError(f"Invalid oracle asset SHA-256 for {path!r}.")
|
| 736 |
+
size = value.get("size")
|
| 737 |
+
if isinstance(size, bool) or not isinstance(size, int) or size <= 0:
|
| 738 |
+
raise RegistryError(f"{asset_context}.size must be a positive byte count.")
|
| 739 |
+
result.append(
|
| 740 |
+
OracleAsset(
|
| 741 |
+
role=role,
|
| 742 |
+
path=path,
|
| 743 |
+
url=url,
|
| 744 |
+
sha256=sha256,
|
| 745 |
+
size=size,
|
| 746 |
+
)
|
| 747 |
+
)
|
| 748 |
+
roles = [asset.role for asset in result]
|
| 749 |
+
paths = [asset.path for asset in result]
|
| 750 |
+
urls = [asset.url for asset in result]
|
| 751 |
+
if (
|
| 752 |
+
len(roles) != len(set(roles))
|
| 753 |
+
or len(paths) != len(set(paths))
|
| 754 |
+
or len(urls) != len(set(urls))
|
| 755 |
+
):
|
| 756 |
+
raise RegistryError(f"{context}.oracle_assets contains duplicate identities.")
|
| 757 |
+
return tuple(result)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def _parse_official_golden(
|
| 761 |
+
table: Mapping[str, Any],
|
| 762 |
+
model_id: str,
|
| 763 |
+
context: str,
|
| 764 |
+
) -> OfficialGolden | None:
|
| 765 |
+
raw = table.get("official_golden")
|
| 766 |
+
if raw is None:
|
| 767 |
+
return None
|
| 768 |
+
if not isinstance(raw, dict) or set(raw) != {"metadata", "tensors"}:
|
| 769 |
+
raise RegistryError(
|
| 770 |
+
f"{context}.official_golden must contain exactly 'metadata' and 'tensors'."
|
| 771 |
+
)
|
| 772 |
+
parsed: dict[str, FileDigest] = {}
|
| 773 |
+
for role in ("metadata", "tensors"):
|
| 774 |
+
value = raw[role]
|
| 775 |
+
if not isinstance(value, str):
|
| 776 |
+
raise RegistryError(f"{context}.official_golden.{role} must be a file digest.")
|
| 777 |
+
digest = FileDigest.parse(value)
|
| 778 |
+
if digest.algorithm != "sha256":
|
| 779 |
+
raise RegistryError(
|
| 780 |
+
f"{context}.official_golden.{role} must use an immutable SHA-256 digest."
|
| 781 |
+
)
|
| 782 |
+
expected = f"tests/goldens/{model_id}.{'json' if role == 'metadata' else 'safetensors'}"
|
| 783 |
+
if digest.path != expected:
|
| 784 |
+
raise RegistryError(f"{context}.official_golden.{role} must use path {expected!r}.")
|
| 785 |
+
parsed[role] = digest
|
| 786 |
+
return OfficialGolden(metadata=parsed["metadata"], tensors=parsed["tensors"])
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def _parse_attention_kernels(raw: object) -> dict[str, AttentionKernelSpec]:
|
| 790 |
+
if not isinstance(raw, list) or not raw:
|
| 791 |
+
raise RegistryError("The manifest must contain [[attention_kernels]] entries.")
|
| 792 |
+
result: dict[str, AttentionKernelSpec] = {}
|
| 793 |
+
expected_variants = {
|
| 794 |
+
"flash_attention_2": "flash_attn2",
|
| 795 |
+
"flash_attention_3": "flash_attn3",
|
| 796 |
+
}
|
| 797 |
+
for index, value in enumerate(raw):
|
| 798 |
+
context = f"attention_kernels[{index}]"
|
| 799 |
+
if not isinstance(value, dict):
|
| 800 |
+
raise RegistryError(f"{context} must be a table.")
|
| 801 |
+
expected_fields = frozenset(
|
| 802 |
+
{
|
| 803 |
+
"implementation",
|
| 804 |
+
"repository",
|
| 805 |
+
"revision",
|
| 806 |
+
"version",
|
| 807 |
+
"expected_variant",
|
| 808 |
+
"dtypes",
|
| 809 |
+
}
|
| 810 |
+
)
|
| 811 |
+
_reject_unknown_fields(value, expected_fields, context)
|
| 812 |
+
implementation = _require_str(value, "implementation", context)
|
| 813 |
+
if implementation not in expected_variants:
|
| 814 |
+
raise RegistryError(f"Unsupported attention kernel {implementation!r}.")
|
| 815 |
+
if implementation in result:
|
| 816 |
+
raise RegistryError(f"Duplicate attention kernel {implementation!r}.")
|
| 817 |
+
repository = _require_str(value, "repository", context)
|
| 818 |
+
if _REPOSITORY_ID_RE.fullmatch(repository) is None:
|
| 819 |
+
raise RegistryError(f"Invalid attention-kernel repository {repository!r}.")
|
| 820 |
+
revision = _require_str(value, "revision", context)
|
| 821 |
+
_validate_revision(revision, f"{context}.revision")
|
| 822 |
+
kernel_version = value.get("version")
|
| 823 |
+
if (
|
| 824 |
+
isinstance(kernel_version, bool)
|
| 825 |
+
or not isinstance(kernel_version, int)
|
| 826 |
+
or kernel_version <= 0
|
| 827 |
+
):
|
| 828 |
+
raise RegistryError(f"{context}.version must be a positive integer.")
|
| 829 |
+
expected_variant = _require_str(value, "expected_variant", context)
|
| 830 |
+
if expected_variant != expected_variants[implementation]:
|
| 831 |
+
raise RegistryError(
|
| 832 |
+
f"{context}.expected_variant must be {expected_variants[implementation]!r}."
|
| 833 |
+
)
|
| 834 |
+
dtypes = _require_str_list(value, "dtypes", context)
|
| 835 |
+
if not set(dtypes).issubset(_ALLOWED_DTYPES):
|
| 836 |
+
raise RegistryError(f"{context}.dtypes contains unsupported dtypes.")
|
| 837 |
+
result[implementation] = AttentionKernelSpec(
|
| 838 |
+
implementation=implementation,
|
| 839 |
+
repository=repository,
|
| 840 |
+
revision=revision,
|
| 841 |
+
version=kernel_version,
|
| 842 |
+
expected_variant=expected_variant,
|
| 843 |
+
dtypes=cast(tuple[DtypeName, ...], dtypes),
|
| 844 |
+
)
|
| 845 |
+
if set(result) != set(expected_variants):
|
| 846 |
+
raise RegistryError("The manifest must pin both FlashAttention kernel versions.")
|
| 847 |
+
return result
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def _parse_upstreams(raw: object) -> dict[str, UpstreamSource]:
|
| 851 |
+
if not isinstance(raw, list) or not raw:
|
| 852 |
+
raise RegistryError("The manifest must contain at least one [[upstreams]] entry.")
|
| 853 |
+
result: dict[str, UpstreamSource] = {}
|
| 854 |
+
paths: set[str] = set()
|
| 855 |
+
for index, value in enumerate(raw):
|
| 856 |
+
context = f"upstreams[{index}]"
|
| 857 |
+
if not isinstance(value, dict):
|
| 858 |
+
raise RegistryError(f"{context} must be a table.")
|
| 859 |
+
_reject_unknown_fields(value, _UPSTREAM_FIELDS, context)
|
| 860 |
+
source_id = _require_str(value, "id", context)
|
| 861 |
+
if _IDENTIFIER_RE.fullmatch(source_id) is None:
|
| 862 |
+
raise RegistryError(f"Invalid upstream ID: {source_id!r}")
|
| 863 |
+
if source_id in result:
|
| 864 |
+
raise RegistryError(f"Duplicate upstream ID: {source_id!r}")
|
| 865 |
+
revision = _require_str(value, "revision", context)
|
| 866 |
+
_validate_revision(revision, f"{context}.revision")
|
| 867 |
+
path = _require_str(value, "path", context)
|
| 868 |
+
try:
|
| 869 |
+
normalized_path = _portable_relative_path(path, f"{context}.path")
|
| 870 |
+
except RegistryError as error:
|
| 871 |
+
raise RegistryError(
|
| 872 |
+
f"{context}.path must be a normalized directory directly under "
|
| 873 |
+
"'vendor/upstream/'."
|
| 874 |
+
) from error
|
| 875 |
+
if (
|
| 876 |
+
normalized_path.parts[:2] != ("vendor", "upstream")
|
| 877 |
+
or len(normalized_path.parts) != 3
|
| 878 |
+
):
|
| 879 |
+
raise RegistryError(
|
| 880 |
+
f"{context}.path must be a normalized directory directly under "
|
| 881 |
+
"'vendor/upstream/'."
|
| 882 |
+
)
|
| 883 |
+
if path in paths:
|
| 884 |
+
raise RegistryError(f"Duplicate upstream path: {path!r}")
|
| 885 |
+
paths.add(path)
|
| 886 |
+
url = _require_str(value, "url", context)
|
| 887 |
+
if not url.startswith("https://github.com/") or not url.endswith(".git"):
|
| 888 |
+
raise RegistryError(f"{context}.url must be an HTTPS GitHub clone URL.")
|
| 889 |
+
license_files = _require_str_list(value, "license_files", context)
|
| 890 |
+
license_digests = _require_digest_list(value, "license_digests", context)
|
| 891 |
+
if tuple(item.path for item in license_digests) != license_files:
|
| 892 |
+
raise RegistryError(
|
| 893 |
+
f"{context}.license_digests must cover license_files in the same order."
|
| 894 |
+
)
|
| 895 |
+
distribution_files = _require_digest_list(value, "distribution_files", context)
|
| 896 |
+
distribution_map = {item.path: item for item in distribution_files}
|
| 897 |
+
for canonical in license_digests:
|
| 898 |
+
distributed = distribution_map.get(canonical.path)
|
| 899 |
+
if distributed is None or distributed.encoded != canonical.encoded:
|
| 900 |
+
raise RegistryError(
|
| 901 |
+
f"{context}.distribution_files must include an exact copy of "
|
| 902 |
+
f"{canonical.path!r}."
|
| 903 |
+
)
|
| 904 |
+
if source_id == "e1":
|
| 905 |
+
required_e1 = {
|
| 906 |
+
"LICENSE",
|
| 907 |
+
"ATTRIBUTION",
|
| 908 |
+
"NOTICE",
|
| 909 |
+
"Apache-2.0.txt",
|
| 910 |
+
"BSD-3-Clause.txt",
|
| 911 |
+
"MODIFICATIONS.md",
|
| 912 |
+
}
|
| 913 |
+
missing_e1 = sorted(required_e1.difference(distribution_map))
|
| 914 |
+
if missing_e1:
|
| 915 |
+
raise RegistryError(f"{context} is missing E1 legal files: {missing_e1}")
|
| 916 |
+
result[source_id] = UpstreamSource(
|
| 917 |
+
id=source_id,
|
| 918 |
+
path=path,
|
| 919 |
+
url=url,
|
| 920 |
+
revision=revision,
|
| 921 |
+
license_expression=_require_str(value, "license", context),
|
| 922 |
+
license_files=license_files,
|
| 923 |
+
license_digests=license_digests,
|
| 924 |
+
distribution_files=distribution_files,
|
| 925 |
+
)
|
| 926 |
+
return result
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def _parse_families(
|
| 930 |
+
raw: object,
|
| 931 |
+
upstreams: Mapping[str, UpstreamSource],
|
| 932 |
+
) -> dict[str, ModelFamily]:
|
| 933 |
+
if not isinstance(raw, dict) or not raw:
|
| 934 |
+
raise RegistryError("The manifest must contain [families.<id>] tables.")
|
| 935 |
+
result: dict[str, ModelFamily] = {}
|
| 936 |
+
for family_id, value in raw.items():
|
| 937 |
+
context = f"families.{family_id}"
|
| 938 |
+
if _IDENTIFIER_RE.fullmatch(family_id) is None or not isinstance(value, dict):
|
| 939 |
+
raise RegistryError(f"Invalid family table: {family_id!r}")
|
| 940 |
+
checkpoint_license = _require_str(value, "checkpoint_license", context)
|
| 941 |
+
hub_license, hub_license_name, hub_license_link = _parse_hub_license(
|
| 942 |
+
value,
|
| 943 |
+
checkpoint_license=checkpoint_license,
|
| 944 |
+
context=context,
|
| 945 |
+
)
|
| 946 |
+
_reject_unknown_fields(value, _FAMILY_FIELDS, context)
|
| 947 |
+
source_ids = _require_str_list(value, "upstreams", context)
|
| 948 |
+
unknown_sources = sorted(set(source_ids).difference(upstreams))
|
| 949 |
+
if unknown_sources:
|
| 950 |
+
raise RegistryError(f"{context} references unknown upstreams: {unknown_sources}")
|
| 951 |
+
tokenizer_mode = _require_str(value, "tokenizer_mode", context)
|
| 952 |
+
if tokenizer_mode not in _ALLOWED_TOKENIZER_MODES:
|
| 953 |
+
raise RegistryError(f"Unsupported tokenizer mode in {context}: {tokenizer_mode!r}")
|
| 954 |
+
public_input = _require_str(value, "public_input", context)
|
| 955 |
+
attention = _require_str_list(value, "attention", context)
|
| 956 |
+
if not set(attention).issubset(_ALLOWED_ATTENTION):
|
| 957 |
+
raise RegistryError(f"Unsupported attention implementation in {context}.")
|
| 958 |
+
dtypes = _require_str_list(value, "dtypes", context)
|
| 959 |
+
if not set(dtypes).issubset(_ALLOWED_DTYPES):
|
| 960 |
+
raise RegistryError(f"Unsupported dtype in {context}.")
|
| 961 |
+
bf16_execution = cast(
|
| 962 |
+
Bf16Execution,
|
| 963 |
+
_require_enum(
|
| 964 |
+
value,
|
| 965 |
+
"bf16_execution",
|
| 966 |
+
context,
|
| 967 |
+
_ALLOWED_BF16_EXECUTIONS,
|
| 968 |
+
),
|
| 969 |
+
)
|
| 970 |
+
precisions = _require_str_list(value, "precisions", context)
|
| 971 |
+
if not set(precisions).issubset(_ALLOWED_PRECISIONS):
|
| 972 |
+
raise RegistryError(f"Unsupported precision policy in {context}.")
|
| 973 |
+
experimental_precisions = _optional_str_list(
|
| 974 |
+
value,
|
| 975 |
+
"experimental_precisions",
|
| 976 |
+
context,
|
| 977 |
+
)
|
| 978 |
+
unknown_experimental_precisions = sorted(
|
| 979 |
+
set(experimental_precisions).difference(precisions)
|
| 980 |
+
)
|
| 981 |
+
if unknown_experimental_precisions:
|
| 982 |
+
raise RegistryError(
|
| 983 |
+
f"{context}.experimental_precisions must be a subset of precisions; "
|
| 984 |
+
f"unknown values: {unknown_experimental_precisions}."
|
| 985 |
+
)
|
| 986 |
+
extra = cast(RuntimeExtra, _require_enum(value, "extra", context, _ALLOWED_EXTRAS))
|
| 987 |
+
vram_tier = cast(
|
| 988 |
+
VramTier,
|
| 989 |
+
_require_enum(value, "vram_tier", context, _ALLOWED_VRAM_TIERS),
|
| 990 |
+
)
|
| 991 |
+
test_tiers_raw = _require_str_list(value, "test_tiers", context)
|
| 992 |
+
unknown_test_tiers = sorted(set(test_tiers_raw).difference(_ALLOWED_TEST_TIERS))
|
| 993 |
+
if unknown_test_tiers:
|
| 994 |
+
raise RegistryError(
|
| 995 |
+
f"{context}.test_tiers contains unsupported tiers: {unknown_test_tiers}."
|
| 996 |
+
)
|
| 997 |
+
test_tiers = cast(tuple[TestTier, ...], test_tiers_raw)
|
| 998 |
+
reference_container = _parse_reference_container(value, context)
|
| 999 |
+
reference_adapter = _parse_reference_adapter(value, context)
|
| 1000 |
+
documentation = _parse_documentation_path(value, context)
|
| 1001 |
+
runtime_paths = _require_str_list(value, "runtime_paths", context)
|
| 1002 |
+
if len(runtime_paths) != len(set(runtime_paths)):
|
| 1003 |
+
raise RegistryError(f"{context}.runtime_paths must not contain duplicates.")
|
| 1004 |
+
for runtime_path in runtime_paths:
|
| 1005 |
+
try:
|
| 1006 |
+
_portable_relative_path(runtime_path, f"{context}.runtime_paths entry")
|
| 1007 |
+
except RegistryError as error:
|
| 1008 |
+
raise RegistryError(
|
| 1009 |
+
f"Unsafe runtime path in {context}: {runtime_path!r}"
|
| 1010 |
+
) from error
|
| 1011 |
+
if runtime_path.startswith("vendor/"):
|
| 1012 |
+
raise RegistryError(f"Unsafe runtime path in {context}: {runtime_path!r}")
|
| 1013 |
+
requires_complete_weight_publication = value.get(
|
| 1014 |
+
"requires_complete_weight_publication",
|
| 1015 |
+
False,
|
| 1016 |
+
)
|
| 1017 |
+
if not isinstance(requires_complete_weight_publication, bool):
|
| 1018 |
+
raise RegistryError(
|
| 1019 |
+
f"{context}.requires_complete_weight_publication must be a boolean."
|
| 1020 |
+
)
|
| 1021 |
+
if "weights_publication_allowed" not in value:
|
| 1022 |
+
raise RegistryError(
|
| 1023 |
+
f"{context}.weights_publication_allowed must be declared explicitly."
|
| 1024 |
+
)
|
| 1025 |
+
weights_publication_allowed = value["weights_publication_allowed"]
|
| 1026 |
+
if not isinstance(weights_publication_allowed, bool):
|
| 1027 |
+
raise RegistryError(f"{context}.weights_publication_allowed must be a boolean.")
|
| 1028 |
+
raw_auto_map = value.get("auto_map")
|
| 1029 |
+
if not isinstance(raw_auto_map, dict) or not raw_auto_map:
|
| 1030 |
+
raise RegistryError(f"{context}.auto_map must be a non-empty table.")
|
| 1031 |
+
auto_map: list[tuple[str, str]] = []
|
| 1032 |
+
for auto_class, class_path in raw_auto_map.items():
|
| 1033 |
+
if auto_class not in _ALLOWED_AUTO_CLASSES or not isinstance(class_path, str):
|
| 1034 |
+
raise RegistryError(f"Invalid AutoClass mapping in {context}: {auto_class!r}")
|
| 1035 |
+
if not class_path.startswith("fastplms.") or class_path.count(".") < 2:
|
| 1036 |
+
raise RegistryError(f"Invalid Python class path in {context}: {class_path!r}")
|
| 1037 |
+
auto_map.append((auto_class, class_path))
|
| 1038 |
+
tokenizer_class = value.get("tokenizer_class")
|
| 1039 |
+
if tokenizer_class is not None:
|
| 1040 |
+
if tokenizer_mode != "tokenizer":
|
| 1041 |
+
raise RegistryError(
|
| 1042 |
+
f"{context}.tokenizer_class requires tokenizer_mode='tokenizer'."
|
| 1043 |
+
)
|
| 1044 |
+
if (
|
| 1045 |
+
not isinstance(tokenizer_class, str)
|
| 1046 |
+
or not tokenizer_class.startswith("fastplms.")
|
| 1047 |
+
or tokenizer_class.count(".") < 2
|
| 1048 |
+
):
|
| 1049 |
+
raise RegistryError(
|
| 1050 |
+
f"Invalid tokenizer class path in {context}: {tokenizer_class!r}"
|
| 1051 |
+
)
|
| 1052 |
+
backbone_model = value.get("backbone_model")
|
| 1053 |
+
if backbone_model is not None and (
|
| 1054 |
+
not isinstance(backbone_model, str)
|
| 1055 |
+
or _IDENTIFIER_RE.fullmatch(backbone_model) is None
|
| 1056 |
+
):
|
| 1057 |
+
raise RegistryError(
|
| 1058 |
+
f"{context}.backbone_model must be a valid manifest model ID."
|
| 1059 |
+
)
|
| 1060 |
+
state_transform = _require_str(value, "state_transform", context)
|
| 1061 |
+
conversion_provenance = _require_str(value, "conversion_provenance", context)
|
| 1062 |
+
required_sections = ("Input:", "Transformation:", "Output:", "Validation:", "Limitation:")
|
| 1063 |
+
missing_sections = [
|
| 1064 |
+
section for section in required_sections if section not in conversion_provenance
|
| 1065 |
+
]
|
| 1066 |
+
if missing_sections or state_transform not in conversion_provenance:
|
| 1067 |
+
raise RegistryError(
|
| 1068 |
+
f"{context}.conversion_provenance must identify {state_transform!r} and "
|
| 1069 |
+
f"contain mechanism-first sections; missing {missing_sections}."
|
| 1070 |
+
)
|
| 1071 |
+
result[family_id] = ModelFamily(
|
| 1072 |
+
id=family_id,
|
| 1073 |
+
architecture=_require_str(value, "architecture", context),
|
| 1074 |
+
upstreams=source_ids,
|
| 1075 |
+
tokenizer_mode=tokenizer_mode,
|
| 1076 |
+
public_input=public_input,
|
| 1077 |
+
extra=extra,
|
| 1078 |
+
reference_container=reference_container,
|
| 1079 |
+
reference_adapter=reference_adapter,
|
| 1080 |
+
attention=attention,
|
| 1081 |
+
dtypes=cast(tuple[DtypeName, ...], dtypes),
|
| 1082 |
+
bf16_execution=bf16_execution,
|
| 1083 |
+
precisions=precisions,
|
| 1084 |
+
experimental_precisions=experimental_precisions,
|
| 1085 |
+
vram_tier=vram_tier,
|
| 1086 |
+
checkpoint_license=checkpoint_license,
|
| 1087 |
+
hub_license=hub_license,
|
| 1088 |
+
state_transform=state_transform,
|
| 1089 |
+
representative=_require_str(value, "representative", context),
|
| 1090 |
+
documentation=documentation,
|
| 1091 |
+
test_tiers=test_tiers,
|
| 1092 |
+
runtime_paths=runtime_paths,
|
| 1093 |
+
auto_map_items=tuple(auto_map),
|
| 1094 |
+
requires_complete_weight_publication=requires_complete_weight_publication,
|
| 1095 |
+
weights_publication_allowed=weights_publication_allowed,
|
| 1096 |
+
tokenizer_class=tokenizer_class,
|
| 1097 |
+
hub_license_name=hub_license_name,
|
| 1098 |
+
hub_license_link=hub_license_link,
|
| 1099 |
+
conversion_provenance=conversion_provenance,
|
| 1100 |
+
backbone_model=backbone_model,
|
| 1101 |
+
)
|
| 1102 |
+
return result
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
def _parse_runtime_assets(
|
| 1106 |
+
raw: object,
|
| 1107 |
+
families: Mapping[str, ModelFamily],
|
| 1108 |
+
) -> dict[str, RuntimeAsset]:
|
| 1109 |
+
if not isinstance(raw, list) or not raw:
|
| 1110 |
+
raise RegistryError("The manifest must contain at least one [[runtime_assets]] entry.")
|
| 1111 |
+
result: dict[str, RuntimeAsset] = {}
|
| 1112 |
+
identities: set[tuple[str, str, str]] = set()
|
| 1113 |
+
for index, value in enumerate(raw):
|
| 1114 |
+
context = f"runtime_assets[{index}]"
|
| 1115 |
+
if not isinstance(value, dict):
|
| 1116 |
+
raise RegistryError(f"{context} must be a table.")
|
| 1117 |
+
_reject_unknown_fields(value, _RUNTIME_ASSET_FIELDS, context)
|
| 1118 |
+
asset_id = _require_str(value, "id", context)
|
| 1119 |
+
if _IDENTIFIER_RE.fullmatch(asset_id) is None:
|
| 1120 |
+
raise RegistryError(f"Invalid runtime asset ID: {asset_id!r}")
|
| 1121 |
+
if asset_id in result:
|
| 1122 |
+
raise RegistryError(f"Duplicate runtime asset ID: {asset_id!r}")
|
| 1123 |
+
repository = _require_str(value, "repository", context)
|
| 1124 |
+
if _REPOSITORY_ID_RE.fullmatch(repository) is None:
|
| 1125 |
+
raise RegistryError(f"{context}.repository must be a Hugging Face repository ID.")
|
| 1126 |
+
revision = _require_str(value, "revision", context)
|
| 1127 |
+
_validate_revision(revision, f"{context}.revision")
|
| 1128 |
+
path = _require_str(value, "path", context)
|
| 1129 |
+
try:
|
| 1130 |
+
normalized_path = _portable_relative_path(path, "Runtime asset path")
|
| 1131 |
+
except RegistryError as error:
|
| 1132 |
+
raise RegistryError(f"Runtime asset path is not portable: {path!r}") from error
|
| 1133 |
+
sha256 = _require_str(value, "sha256", context)
|
| 1134 |
+
if len(sha256) != 64 or _HEX_RE.fullmatch(sha256) is None:
|
| 1135 |
+
raise RegistryError(f"Invalid runtime asset SHA-256 for {path!r}.")
|
| 1136 |
+
size = value.get("size")
|
| 1137 |
+
if isinstance(size, bool) or not isinstance(size, int) or size <= 0:
|
| 1138 |
+
raise RegistryError(f"{context}.size must be a positive byte count.")
|
| 1139 |
+
consumer_family = _require_str(value, "consumer_family", context)
|
| 1140 |
+
if consumer_family not in families:
|
| 1141 |
+
raise RegistryError(
|
| 1142 |
+
f"{context}.consumer_family references unknown family {consumer_family!r}."
|
| 1143 |
+
)
|
| 1144 |
+
trust_kind = cast(
|
| 1145 |
+
RuntimeAssetTrustKind,
|
| 1146 |
+
_require_enum(
|
| 1147 |
+
value,
|
| 1148 |
+
"trust_kind",
|
| 1149 |
+
context,
|
| 1150 |
+
_ALLOWED_RUNTIME_ASSET_TRUST_KINDS,
|
| 1151 |
+
),
|
| 1152 |
+
)
|
| 1153 |
+
license_expression = _require_str(value, "license", context)
|
| 1154 |
+
offline_behavior = _require_str(value, "offline_behavior", context)
|
| 1155 |
+
if offline_behavior not in _ALLOWED_RUNTIME_ASSET_OFFLINE_BEHAVIORS:
|
| 1156 |
+
raise RegistryError(
|
| 1157 |
+
f"{context}.offline_behavior is unsupported: {offline_behavior!r}."
|
| 1158 |
+
)
|
| 1159 |
+
if trust_kind == "hash_pinned_pickle" and normalized_path.suffix != ".pkl":
|
| 1160 |
+
raise RegistryError(
|
| 1161 |
+
f"{context}.path must end in '.pkl' for trust_kind='hash_pinned_pickle'."
|
| 1162 |
+
)
|
| 1163 |
+
identity = (repository, revision, path)
|
| 1164 |
+
if identity in identities:
|
| 1165 |
+
raise RegistryError(f"Duplicate runtime asset identity: {identity!r}")
|
| 1166 |
+
identities.add(identity)
|
| 1167 |
+
result[asset_id] = RuntimeAsset(
|
| 1168 |
+
id=asset_id,
|
| 1169 |
+
repository=repository,
|
| 1170 |
+
revision=revision,
|
| 1171 |
+
path=path,
|
| 1172 |
+
sha256=sha256,
|
| 1173 |
+
size=size,
|
| 1174 |
+
consumer_family=consumer_family,
|
| 1175 |
+
trust_kind=trust_kind,
|
| 1176 |
+
license_expression=license_expression,
|
| 1177 |
+
offline_behavior=offline_behavior,
|
| 1178 |
+
)
|
| 1179 |
+
return result
|
| 1180 |
+
|
| 1181 |
+
|
| 1182 |
+
def _parse_models(
|
| 1183 |
+
raw: object,
|
| 1184 |
+
families: Mapping[str, ModelFamily],
|
| 1185 |
+
) -> dict[str, ModelSpec]:
|
| 1186 |
+
if not isinstance(raw, list) or not raw:
|
| 1187 |
+
raise RegistryError("The manifest must contain at least one [[models]] entry.")
|
| 1188 |
+
result: dict[str, ModelSpec] = {}
|
| 1189 |
+
fast_repositories: set[str] = set()
|
| 1190 |
+
for index, value in enumerate(raw):
|
| 1191 |
+
context = f"models[{index}]"
|
| 1192 |
+
if not isinstance(value, dict):
|
| 1193 |
+
raise RegistryError(f"{context} must be a table.")
|
| 1194 |
+
_reject_unknown_fields(value, _MODEL_FIELDS, context)
|
| 1195 |
+
model_id = _require_str(value, "id", context)
|
| 1196 |
+
if _IDENTIFIER_RE.fullmatch(model_id) is None:
|
| 1197 |
+
raise RegistryError(f"Invalid model ID: {model_id!r}")
|
| 1198 |
+
if model_id in result:
|
| 1199 |
+
raise RegistryError(f"Duplicate model ID: {model_id!r}")
|
| 1200 |
+
family_id = _require_str(value, "family", context)
|
| 1201 |
+
if family_id not in families:
|
| 1202 |
+
raise RegistryError(f"{context} references unknown family {family_id!r}.")
|
| 1203 |
+
fast = _parse_checkpoint(value, "fast", context)
|
| 1204 |
+
official = _parse_checkpoint(value, "official", context)
|
| 1205 |
+
if fast.repo_id in fast_repositories:
|
| 1206 |
+
raise RegistryError(f"Duplicate FastPLMs repository ID: {fast.repo_id!r}")
|
| 1207 |
+
fast_repositories.add(fast.repo_id)
|
| 1208 |
+
family = families[family_id]
|
| 1209 |
+
oracle_assets = _parse_oracle_assets(value, context)
|
| 1210 |
+
official_golden = _parse_official_golden(value, model_id, context)
|
| 1211 |
+
size_category = _require_str(value, "size_category", context)
|
| 1212 |
+
if size_category not in _ALLOWED_SIZE_CATEGORIES:
|
| 1213 |
+
raise RegistryError(f"Unsupported size category in {context}: {size_category!r}")
|
| 1214 |
+
generation_contract = cast(
|
| 1215 |
+
GenerationContract,
|
| 1216 |
+
_require_enum(
|
| 1217 |
+
value,
|
| 1218 |
+
"generation_contract",
|
| 1219 |
+
context,
|
| 1220 |
+
_ALLOWED_GENERATION_CONTRACTS,
|
| 1221 |
+
),
|
| 1222 |
+
)
|
| 1223 |
+
if family.tokenizer_mode == "structure" and size_category != "structure":
|
| 1224 |
+
raise RegistryError(
|
| 1225 |
+
f"Structure checkpoint {model_id!r} must use size_category='structure'."
|
| 1226 |
+
)
|
| 1227 |
+
artifact_source = value.get("artifact_source", "fast")
|
| 1228 |
+
if artifact_source not in {"fast", "official"}:
|
| 1229 |
+
raise RegistryError(f"{context}.artifact_source must be 'fast' or 'official'.")
|
| 1230 |
+
canonical_state_sha256 = value.get("canonical_state_sha256")
|
| 1231 |
+
if artifact_source == "official":
|
| 1232 |
+
if (
|
| 1233 |
+
not isinstance(canonical_state_sha256, str)
|
| 1234 |
+
or len(canonical_state_sha256) != 64
|
| 1235 |
+
or _HEX_RE.fullmatch(canonical_state_sha256) is None
|
| 1236 |
+
):
|
| 1237 |
+
raise RegistryError(
|
| 1238 |
+
f"{context}.canonical_state_sha256 must be a SHA-256 commitment "
|
| 1239 |
+
"for an official-source artifact."
|
| 1240 |
+
)
|
| 1241 |
+
elif canonical_state_sha256 is not None:
|
| 1242 |
+
raise RegistryError(
|
| 1243 |
+
f"{context}.canonical_state_sha256 is restricted to official-source artifacts."
|
| 1244 |
+
)
|
| 1245 |
+
if family.tokenizer_mode == "tokenizer" and not any(
|
| 1246 |
+
"tokenizer" in item.path or "vocab" in item.path for item in fast.files
|
| 1247 |
+
):
|
| 1248 |
+
raise RegistryError(f"{context} does not pin a tokenizer asset.")
|
| 1249 |
+
tokenizer_source_id = value.get("tokenizer_source")
|
| 1250 |
+
if tokenizer_source_id is not None and (
|
| 1251 |
+
family.tokenizer_mode != "tokenizer"
|
| 1252 |
+
or not isinstance(tokenizer_source_id, str)
|
| 1253 |
+
or _IDENTIFIER_RE.fullmatch(tokenizer_source_id) is None
|
| 1254 |
+
):
|
| 1255 |
+
raise RegistryError(f"{context}.tokenizer_source is invalid.")
|
| 1256 |
+
notes = value.get("notes", "")
|
| 1257 |
+
if not isinstance(notes, str):
|
| 1258 |
+
raise RegistryError(f"{context}.notes must be a string.")
|
| 1259 |
+
msa_conditioning = value.get("msa_conditioning")
|
| 1260 |
+
if family_id == "esmfold2":
|
| 1261 |
+
if not isinstance(msa_conditioning, bool):
|
| 1262 |
+
raise RegistryError(
|
| 1263 |
+
f"{context}.msa_conditioning must be an explicit boolean for "
|
| 1264 |
+
"ESMFold2 checkpoints."
|
| 1265 |
+
)
|
| 1266 |
+
elif "msa_conditioning" in value:
|
| 1267 |
+
raise RegistryError(
|
| 1268 |
+
f"{context}.msa_conditioning is only valid for ESMFold2 checkpoints."
|
| 1269 |
+
)
|
| 1270 |
+
raw_auto_map = value.get("auto_map")
|
| 1271 |
+
auto_map: list[tuple[str, str]] = []
|
| 1272 |
+
if raw_auto_map is not None:
|
| 1273 |
+
if not isinstance(raw_auto_map, dict) or not raw_auto_map:
|
| 1274 |
+
raise RegistryError(f"{context}.auto_map must be a non-empty table.")
|
| 1275 |
+
for auto_class, class_path in raw_auto_map.items():
|
| 1276 |
+
if auto_class not in _ALLOWED_AUTO_CLASSES or not isinstance(class_path, str):
|
| 1277 |
+
raise RegistryError(f"Invalid AutoClass mapping in {context}: {auto_class!r}")
|
| 1278 |
+
if not class_path.startswith("fastplms.") or class_path.count(".") < 2:
|
| 1279 |
+
raise RegistryError(f"Invalid Python class path in {context}: {class_path!r}")
|
| 1280 |
+
auto_map.append((auto_class, class_path))
|
| 1281 |
+
result[model_id] = ModelSpec(
|
| 1282 |
+
id=model_id,
|
| 1283 |
+
family=family,
|
| 1284 |
+
fast=fast,
|
| 1285 |
+
official=official,
|
| 1286 |
+
size_category=size_category,
|
| 1287 |
+
generation_contract=generation_contract,
|
| 1288 |
+
oracle_assets=oracle_assets,
|
| 1289 |
+
official_golden=official_golden,
|
| 1290 |
+
artifact_source=artifact_source,
|
| 1291 |
+
canonical_state_sha256=canonical_state_sha256,
|
| 1292 |
+
tokenizer_source_id=tokenizer_source_id,
|
| 1293 |
+
auto_map_items=tuple(auto_map),
|
| 1294 |
+
notes=notes,
|
| 1295 |
+
msa_conditioning=msa_conditioning,
|
| 1296 |
+
)
|
| 1297 |
+
return result
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
def _validate_registry(
|
| 1301 |
+
upstreams: Mapping[str, UpstreamSource],
|
| 1302 |
+
attention_kernels: Mapping[str, AttentionKernelSpec],
|
| 1303 |
+
families: Mapping[str, ModelFamily],
|
| 1304 |
+
models: Mapping[str, ModelSpec],
|
| 1305 |
+
) -> None:
|
| 1306 |
+
for spec in models.values():
|
| 1307 |
+
if spec.tokenizer_source_id is None:
|
| 1308 |
+
continue
|
| 1309 |
+
source = models.get(spec.tokenizer_source_id)
|
| 1310 |
+
if source is None:
|
| 1311 |
+
raise RegistryError(
|
| 1312 |
+
f"Model {spec.id!r} references unknown tokenizer source "
|
| 1313 |
+
f"{spec.tokenizer_source_id!r}."
|
| 1314 |
+
)
|
| 1315 |
+
if not any(
|
| 1316 |
+
PurePosixPath(item.path).name
|
| 1317 |
+
in {
|
| 1318 |
+
"added_tokens.json",
|
| 1319 |
+
"merges.txt",
|
| 1320 |
+
"sentencepiece.bpe.model",
|
| 1321 |
+
"special_tokens_map.json",
|
| 1322 |
+
"spiece.model",
|
| 1323 |
+
"tokenizer.json",
|
| 1324 |
+
"tokenizer_config.json",
|
| 1325 |
+
"vocab.json",
|
| 1326 |
+
"vocab.txt",
|
| 1327 |
+
}
|
| 1328 |
+
for item in source.official.files
|
| 1329 |
+
):
|
| 1330 |
+
raise RegistryError(
|
| 1331 |
+
f"Tokenizer source {source.id!r} has no official tokenizer assets."
|
| 1332 |
+
)
|
| 1333 |
+
expected_esmfold2 = {
|
| 1334 |
+
"esmfold2": ("Synthyra/ESMFold2", "biohub/ESMFold2"),
|
| 1335 |
+
"esmfold2_fast": ("Synthyra/ESMFold2-Fast", "biohub/ESMFold2-Fast"),
|
| 1336 |
+
"esmfold2_experimental_cutoff2025": (
|
| 1337 |
+
"Synthyra/ESMFold2-Experimental-Cutoff2025",
|
| 1338 |
+
"biohub/ESMFold2-Experimental-Cutoff2025",
|
| 1339 |
+
),
|
| 1340 |
+
"esmfold2_experimental_fast_cutoff2025": (
|
| 1341 |
+
"Synthyra/ESMFold2-Experimental-Fast-Cutoff2025",
|
| 1342 |
+
"biohub/ESMFold2-Experimental-Fast-Cutoff2025",
|
| 1343 |
+
),
|
| 1344 |
+
}
|
| 1345 |
+
actual_esmfold2 = {
|
| 1346 |
+
model.id: (model.fast.repo_id, model.official.repo_id)
|
| 1347 |
+
for model in models.values()
|
| 1348 |
+
if model.family.id == "esmfold2"
|
| 1349 |
+
}
|
| 1350 |
+
if actual_esmfold2 != expected_esmfold2:
|
| 1351 |
+
raise RegistryError(
|
| 1352 |
+
"ESMFold2 support must contain exactly the four approved model IDs and "
|
| 1353 |
+
"official/Synthyra repositories."
|
| 1354 |
+
)
|
| 1355 |
+
|
| 1356 |
+
golden_paths: list[str] = []
|
| 1357 |
+
for model in models.values():
|
| 1358 |
+
if model.official_golden is not None:
|
| 1359 |
+
golden_paths.extend(
|
| 1360 |
+
(
|
| 1361 |
+
model.official_golden.metadata.path,
|
| 1362 |
+
model.official_golden.tensors.path,
|
| 1363 |
+
)
|
| 1364 |
+
)
|
| 1365 |
+
if len(golden_paths) != len(set(golden_paths)):
|
| 1366 |
+
raise RegistryError("Official golden paths must be unique across model declarations.")
|
| 1367 |
+
unused_upstreams = sorted(
|
| 1368 |
+
set(upstreams).difference(
|
| 1369 |
+
source for family in families.values() for source in family.upstreams
|
| 1370 |
+
)
|
| 1371 |
+
)
|
| 1372 |
+
if unused_upstreams:
|
| 1373 |
+
raise RegistryError(
|
| 1374 |
+
f"Upstream sources are not connected to a model family: {unused_upstreams}"
|
| 1375 |
+
)
|
| 1376 |
+
advertised_flash = {
|
| 1377 |
+
implementation
|
| 1378 |
+
for family in families.values()
|
| 1379 |
+
for implementation in family.attention
|
| 1380 |
+
if implementation.startswith("flash_attention_")
|
| 1381 |
+
}
|
| 1382 |
+
missing_kernels = sorted(advertised_flash.difference(attention_kernels))
|
| 1383 |
+
if missing_kernels:
|
| 1384 |
+
raise RegistryError(
|
| 1385 |
+
f"Advertised FlashAttention backends lack kernel specs: {missing_kernels}."
|
| 1386 |
+
)
|
| 1387 |
+
for family in families.values():
|
| 1388 |
+
for implementation in family.attention:
|
| 1389 |
+
kernel = attention_kernels.get(implementation)
|
| 1390 |
+
if kernel is not None and not set(family.dtypes).intersection(kernel.dtypes):
|
| 1391 |
+
raise RegistryError(
|
| 1392 |
+
f"Family {family.id!r} and attention kernel {implementation!r} "
|
| 1393 |
+
"have no supported dtype in common."
|
| 1394 |
+
)
|
| 1395 |
+
family_models = [model for model in models.values() if model.family.id == family.id]
|
| 1396 |
+
if not family_models:
|
| 1397 |
+
raise RegistryError(f"Family {family.id!r} has no checkpoints.")
|
| 1398 |
+
representative = models.get(family.representative)
|
| 1399 |
+
if representative is None or representative.family.id != family.id:
|
| 1400 |
+
raise RegistryError(
|
| 1401 |
+
f"Family {family.id!r} has invalid representative {family.representative!r}."
|
| 1402 |
+
)
|
| 1403 |
+
if family.backbone_model is not None and family.backbone_model not in models:
|
| 1404 |
+
raise RegistryError(
|
| 1405 |
+
f"Family {family.id!r} references unknown backbone model "
|
| 1406 |
+
f"{family.backbone_model!r}."
|
| 1407 |
+
)
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
def _load_manifest_bytes(raw_bytes: bytes) -> ModelRegistry:
|
| 1411 |
+
try:
|
| 1412 |
+
data = tomllib.loads(raw_bytes.decode("utf-8"))
|
| 1413 |
+
except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error:
|
| 1414 |
+
raise RegistryError(f"Unable to parse model manifest: {error}") from error
|
| 1415 |
+
_reject_unknown_fields(data, _ROOT_FIELDS, "manifest")
|
| 1416 |
+
if data.get("schema_version") != 1:
|
| 1417 |
+
raise RegistryError("Unsupported model manifest schema_version; expected 1.")
|
| 1418 |
+
legal_files = _require_digest_list(data, "legal_files", "manifest")
|
| 1419 |
+
required_legal_paths = {"LICENSE", "THIRD_PARTY_NOTICES.md"}
|
| 1420 |
+
if {item.path for item in legal_files} != required_legal_paths:
|
| 1421 |
+
raise RegistryError("manifest.legal_files must contain LICENSE and THIRD_PARTY_NOTICES.md.")
|
| 1422 |
+
attention_kernels = _parse_attention_kernels(data.get("attention_kernels"))
|
| 1423 |
+
upstreams = _parse_upstreams(data.get("upstreams"))
|
| 1424 |
+
families = _parse_families(data.get("families"), upstreams)
|
| 1425 |
+
runtime_assets = _parse_runtime_assets(data.get("runtime_assets"), families)
|
| 1426 |
+
models = _parse_models(data.get("models"), families)
|
| 1427 |
+
_validate_registry(upstreams, attention_kernels, families, models)
|
| 1428 |
+
return ModelRegistry(
|
| 1429 |
+
schema_version=1,
|
| 1430 |
+
upstreams=upstreams,
|
| 1431 |
+
attention_kernels=attention_kernels,
|
| 1432 |
+
families=families,
|
| 1433 |
+
models=models,
|
| 1434 |
+
runtime_assets=runtime_assets,
|
| 1435 |
+
legal_files=legal_files,
|
| 1436 |
+
)
|
| 1437 |
+
|
| 1438 |
+
|
| 1439 |
+
def load_model_registry(path: str | Path | None = None) -> ModelRegistry:
|
| 1440 |
+
"""Load and validate a model manifest without importing model code."""
|
| 1441 |
+
|
| 1442 |
+
if path is None:
|
| 1443 |
+
manifest = resources.files("fastplms").joinpath("models.toml")
|
| 1444 |
+
return _load_manifest_bytes(manifest.read_bytes())
|
| 1445 |
+
return _load_manifest_bytes(Path(path).read_bytes())
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
@lru_cache(maxsize=1)
|
| 1449 |
+
def get_model_registry() -> ModelRegistry:
|
| 1450 |
+
"""Return the validated package registry, cached after its first read."""
|
| 1451 |
+
|
| 1452 |
+
return load_model_registry()
|
| 1453 |
+
|
| 1454 |
+
|
| 1455 |
+
def get_model_spec(model_id: str) -> ModelSpec:
|
| 1456 |
+
"""Return one model specification by its stable manifest ID."""
|
| 1457 |
+
|
| 1458 |
+
try:
|
| 1459 |
+
return get_model_registry()[model_id]
|
| 1460 |
+
except KeyError as error:
|
| 1461 |
+
supported = ", ".join(get_model_registry())
|
| 1462 |
+
raise KeyError(
|
| 1463 |
+
f"Unknown FastPLMs model ID {model_id!r}. Supported IDs: {supported}"
|
| 1464 |
+
) from error
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
__all__ = [
|
| 1468 |
+
"HUB_LICENSE_IDENTIFIERS",
|
| 1469 |
+
"CheckpointSource",
|
| 1470 |
+
"FileDigest",
|
| 1471 |
+
"GenerationContract",
|
| 1472 |
+
"ModelFamily",
|
| 1473 |
+
"ModelRegistry",
|
| 1474 |
+
"ModelSpec",
|
| 1475 |
+
"OracleAsset",
|
| 1476 |
+
"RegistryError",
|
| 1477 |
+
"RuntimeAsset",
|
| 1478 |
+
"RuntimeAssetTrustKind",
|
| 1479 |
+
"RuntimeExtra",
|
| 1480 |
+
"TestTier",
|
| 1481 |
+
"UpstreamSource",
|
| 1482 |
+
"VramTier",
|
| 1483 |
+
"get_model_registry",
|
| 1484 |
+
"get_model_spec",
|
| 1485 |
+
"load_model_registry",
|
| 1486 |
+
]
|
fastplms/runtime.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit, reversible Torch runtime configuration.
|
| 2 |
+
|
| 3 |
+
Importing FastPLMs does not change global Torch settings. Callers that want a
|
| 4 |
+
runtime profile opt in with :func:`runtime_profile` and receive their previous
|
| 5 |
+
settings back when the context exits.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from contextlib import contextmanager
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from typing import TYPE_CHECKING, Literal
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from collections.abc import Iterator
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
MatmulPrecision = Literal["highest", "high", "medium"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True, slots=True)
|
| 22 |
+
class RuntimeProfile:
|
| 23 |
+
"""Requested Torch settings for a bounded inference or training block."""
|
| 24 |
+
|
| 25 |
+
float32_matmul_precision: MatmulPrecision = "highest"
|
| 26 |
+
allow_tf32: bool | None = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@contextmanager
|
| 30 |
+
def runtime_profile(profile: RuntimeProfile | None = None) -> Iterator[None]:
|
| 31 |
+
"""Apply a Torch runtime profile and restore the previous global settings.
|
| 32 |
+
|
| 33 |
+
The default profile requests the highest float32 matrix-multiplication
|
| 34 |
+
precision and leaves TF32 policy unchanged. Torch is imported only when the
|
| 35 |
+
context is entered.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
import torch
|
| 39 |
+
|
| 40 |
+
selected = profile or RuntimeProfile()
|
| 41 |
+
previous_matmul_precision = torch.get_float32_matmul_precision()
|
| 42 |
+
matmul_backend = getattr(getattr(torch.backends, "cuda", None), "matmul", None)
|
| 43 |
+
cudnn_backend = getattr(torch.backends, "cudnn", None)
|
| 44 |
+
previous_matmul_tf32 = (
|
| 45 |
+
getattr(matmul_backend, "allow_tf32", None) if matmul_backend is not None else None
|
| 46 |
+
)
|
| 47 |
+
previous_cudnn_tf32 = (
|
| 48 |
+
getattr(cudnn_backend, "allow_tf32", None) if cudnn_backend is not None else None
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
torch.set_float32_matmul_precision(selected.float32_matmul_precision)
|
| 52 |
+
if selected.allow_tf32 is not None:
|
| 53 |
+
if matmul_backend is not None and hasattr(matmul_backend, "allow_tf32"):
|
| 54 |
+
matmul_backend.allow_tf32 = selected.allow_tf32
|
| 55 |
+
if cudnn_backend is not None and hasattr(cudnn_backend, "allow_tf32"):
|
| 56 |
+
cudnn_backend.allow_tf32 = selected.allow_tf32
|
| 57 |
+
try:
|
| 58 |
+
yield
|
| 59 |
+
finally:
|
| 60 |
+
torch.set_float32_matmul_precision(previous_matmul_precision)
|
| 61 |
+
if selected.allow_tf32 is not None:
|
| 62 |
+
if matmul_backend is not None and previous_matmul_tf32 is not None:
|
| 63 |
+
matmul_backend.allow_tf32 = previous_matmul_tf32
|
| 64 |
+
if cudnn_backend is not None and previous_cudnn_tf32 is not None:
|
| 65 |
+
cudnn_backend.allow_tf32 = previous_cudnn_tf32
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
__all__ = ["MatmulPrecision", "RuntimeProfile", "runtime_profile"]
|
fastplms_bundle.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"decoder_start_token_id": 0,
|
| 4 |
+
"eos_token_id": 1,
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"transformers_version": "4.26.1"
|
| 7 |
+
}
|
model.safetensors → model-00001-of-00002.safetensors
RENAMED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c0c297f60bcf81c732cdfeae6e99e140272807eb52afd70356fc6fdfa94e5a8
|
| 3 |
+
size 5332161168
|
model-00002-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f3d425d3e8741ccbdd925446559a9bf317c2c91e328f2eee44924423b56e3a3d
|
| 3 |
+
size 2184524400
|
model.safetensors.index.json
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_size": 7516590080
|
| 4 |
+
},
|
| 5 |
+
"weight_map": {
|
| 6 |
+
"decoder.block.0.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 7 |
+
"decoder.block.0.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 8 |
+
"decoder.block.0.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 9 |
+
"decoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight": "model-00001-of-00002.safetensors",
|
| 10 |
+
"decoder.block.0.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 11 |
+
"decoder.block.0.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 12 |
+
"decoder.block.0.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 13 |
+
"decoder.block.0.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 14 |
+
"decoder.block.0.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 15 |
+
"decoder.block.0.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 16 |
+
"decoder.block.0.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 17 |
+
"decoder.block.0.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 18 |
+
"decoder.block.0.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 19 |
+
"decoder.block.0.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 20 |
+
"decoder.block.0.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 21 |
+
"decoder.block.1.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 22 |
+
"decoder.block.1.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 23 |
+
"decoder.block.1.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 24 |
+
"decoder.block.1.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 25 |
+
"decoder.block.1.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 26 |
+
"decoder.block.1.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 27 |
+
"decoder.block.1.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 28 |
+
"decoder.block.1.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 29 |
+
"decoder.block.1.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 30 |
+
"decoder.block.1.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 31 |
+
"decoder.block.1.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 32 |
+
"decoder.block.1.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 33 |
+
"decoder.block.1.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 34 |
+
"decoder.block.1.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 35 |
+
"decoder.block.10.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 36 |
+
"decoder.block.10.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 37 |
+
"decoder.block.10.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 38 |
+
"decoder.block.10.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 39 |
+
"decoder.block.10.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 40 |
+
"decoder.block.10.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 41 |
+
"decoder.block.10.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 42 |
+
"decoder.block.10.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 43 |
+
"decoder.block.10.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 44 |
+
"decoder.block.10.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 45 |
+
"decoder.block.10.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 46 |
+
"decoder.block.10.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 47 |
+
"decoder.block.10.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 48 |
+
"decoder.block.10.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 49 |
+
"decoder.block.11.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 50 |
+
"decoder.block.11.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 51 |
+
"decoder.block.11.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 52 |
+
"decoder.block.11.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 53 |
+
"decoder.block.11.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 54 |
+
"decoder.block.11.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 55 |
+
"decoder.block.11.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 56 |
+
"decoder.block.11.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 57 |
+
"decoder.block.11.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 58 |
+
"decoder.block.11.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 59 |
+
"decoder.block.11.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 60 |
+
"decoder.block.11.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 61 |
+
"decoder.block.11.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 62 |
+
"decoder.block.11.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 63 |
+
"decoder.block.12.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 64 |
+
"decoder.block.12.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 65 |
+
"decoder.block.12.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 66 |
+
"decoder.block.12.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 67 |
+
"decoder.block.12.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 68 |
+
"decoder.block.12.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 69 |
+
"decoder.block.12.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 70 |
+
"decoder.block.12.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 71 |
+
"decoder.block.12.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 72 |
+
"decoder.block.12.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 73 |
+
"decoder.block.12.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 74 |
+
"decoder.block.12.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 75 |
+
"decoder.block.12.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 76 |
+
"decoder.block.12.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 77 |
+
"decoder.block.13.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 78 |
+
"decoder.block.13.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 79 |
+
"decoder.block.13.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 80 |
+
"decoder.block.13.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 81 |
+
"decoder.block.13.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 82 |
+
"decoder.block.13.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 83 |
+
"decoder.block.13.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 84 |
+
"decoder.block.13.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 85 |
+
"decoder.block.13.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 86 |
+
"decoder.block.13.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 87 |
+
"decoder.block.13.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 88 |
+
"decoder.block.13.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 89 |
+
"decoder.block.13.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 90 |
+
"decoder.block.13.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 91 |
+
"decoder.block.14.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 92 |
+
"decoder.block.14.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 93 |
+
"decoder.block.14.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 94 |
+
"decoder.block.14.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 95 |
+
"decoder.block.14.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 96 |
+
"decoder.block.14.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 97 |
+
"decoder.block.14.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 98 |
+
"decoder.block.14.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 99 |
+
"decoder.block.14.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 100 |
+
"decoder.block.14.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 101 |
+
"decoder.block.14.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 102 |
+
"decoder.block.14.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 103 |
+
"decoder.block.14.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 104 |
+
"decoder.block.14.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 105 |
+
"decoder.block.15.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 106 |
+
"decoder.block.15.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 107 |
+
"decoder.block.15.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 108 |
+
"decoder.block.15.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 109 |
+
"decoder.block.15.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 110 |
+
"decoder.block.15.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 111 |
+
"decoder.block.15.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 112 |
+
"decoder.block.15.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 113 |
+
"decoder.block.15.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 114 |
+
"decoder.block.15.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 115 |
+
"decoder.block.15.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 116 |
+
"decoder.block.15.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 117 |
+
"decoder.block.15.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 118 |
+
"decoder.block.15.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 119 |
+
"decoder.block.16.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 120 |
+
"decoder.block.16.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 121 |
+
"decoder.block.16.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 122 |
+
"decoder.block.16.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 123 |
+
"decoder.block.16.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 124 |
+
"decoder.block.16.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 125 |
+
"decoder.block.16.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 126 |
+
"decoder.block.16.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 127 |
+
"decoder.block.16.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 128 |
+
"decoder.block.16.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 129 |
+
"decoder.block.16.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 130 |
+
"decoder.block.16.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 131 |
+
"decoder.block.16.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 132 |
+
"decoder.block.16.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 133 |
+
"decoder.block.17.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 134 |
+
"decoder.block.17.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 135 |
+
"decoder.block.17.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 136 |
+
"decoder.block.17.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 137 |
+
"decoder.block.17.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 138 |
+
"decoder.block.17.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 139 |
+
"decoder.block.17.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 140 |
+
"decoder.block.17.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 141 |
+
"decoder.block.17.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 142 |
+
"decoder.block.17.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 143 |
+
"decoder.block.17.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 144 |
+
"decoder.block.17.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 145 |
+
"decoder.block.17.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 146 |
+
"decoder.block.17.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 147 |
+
"decoder.block.18.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 148 |
+
"decoder.block.18.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 149 |
+
"decoder.block.18.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 150 |
+
"decoder.block.18.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 151 |
+
"decoder.block.18.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 152 |
+
"decoder.block.18.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 153 |
+
"decoder.block.18.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 154 |
+
"decoder.block.18.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 155 |
+
"decoder.block.18.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 156 |
+
"decoder.block.18.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 157 |
+
"decoder.block.18.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 158 |
+
"decoder.block.18.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 159 |
+
"decoder.block.18.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 160 |
+
"decoder.block.18.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 161 |
+
"decoder.block.19.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 162 |
+
"decoder.block.19.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 163 |
+
"decoder.block.19.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 164 |
+
"decoder.block.19.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 165 |
+
"decoder.block.19.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 166 |
+
"decoder.block.19.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 167 |
+
"decoder.block.19.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 168 |
+
"decoder.block.19.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 169 |
+
"decoder.block.19.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 170 |
+
"decoder.block.19.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 171 |
+
"decoder.block.19.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 172 |
+
"decoder.block.19.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 173 |
+
"decoder.block.19.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 174 |
+
"decoder.block.19.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 175 |
+
"decoder.block.2.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 176 |
+
"decoder.block.2.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 177 |
+
"decoder.block.2.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 178 |
+
"decoder.block.2.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 179 |
+
"decoder.block.2.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 180 |
+
"decoder.block.2.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 181 |
+
"decoder.block.2.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 182 |
+
"decoder.block.2.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 183 |
+
"decoder.block.2.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 184 |
+
"decoder.block.2.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 185 |
+
"decoder.block.2.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 186 |
+
"decoder.block.2.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 187 |
+
"decoder.block.2.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 188 |
+
"decoder.block.2.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 189 |
+
"decoder.block.20.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 190 |
+
"decoder.block.20.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 191 |
+
"decoder.block.20.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 192 |
+
"decoder.block.20.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 193 |
+
"decoder.block.20.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 194 |
+
"decoder.block.20.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 195 |
+
"decoder.block.20.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 196 |
+
"decoder.block.20.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 197 |
+
"decoder.block.20.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 198 |
+
"decoder.block.20.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 199 |
+
"decoder.block.20.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 200 |
+
"decoder.block.20.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 201 |
+
"decoder.block.20.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 202 |
+
"decoder.block.20.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 203 |
+
"decoder.block.21.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 204 |
+
"decoder.block.21.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 205 |
+
"decoder.block.21.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 206 |
+
"decoder.block.21.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 207 |
+
"decoder.block.21.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 208 |
+
"decoder.block.21.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 209 |
+
"decoder.block.21.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 210 |
+
"decoder.block.21.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 211 |
+
"decoder.block.21.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 212 |
+
"decoder.block.21.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 213 |
+
"decoder.block.21.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 214 |
+
"decoder.block.21.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 215 |
+
"decoder.block.21.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 216 |
+
"decoder.block.21.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 217 |
+
"decoder.block.22.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 218 |
+
"decoder.block.22.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 219 |
+
"decoder.block.22.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 220 |
+
"decoder.block.22.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 221 |
+
"decoder.block.22.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 222 |
+
"decoder.block.22.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 223 |
+
"decoder.block.22.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 224 |
+
"decoder.block.22.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 225 |
+
"decoder.block.22.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 226 |
+
"decoder.block.22.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 227 |
+
"decoder.block.22.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 228 |
+
"decoder.block.22.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 229 |
+
"decoder.block.22.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 230 |
+
"decoder.block.22.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 231 |
+
"decoder.block.23.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 232 |
+
"decoder.block.23.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 233 |
+
"decoder.block.23.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 234 |
+
"decoder.block.23.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 235 |
+
"decoder.block.23.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 236 |
+
"decoder.block.23.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 237 |
+
"decoder.block.23.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 238 |
+
"decoder.block.23.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 239 |
+
"decoder.block.23.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 240 |
+
"decoder.block.23.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 241 |
+
"decoder.block.23.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 242 |
+
"decoder.block.23.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 243 |
+
"decoder.block.23.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 244 |
+
"decoder.block.23.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 245 |
+
"decoder.block.3.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 246 |
+
"decoder.block.3.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 247 |
+
"decoder.block.3.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 248 |
+
"decoder.block.3.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 249 |
+
"decoder.block.3.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 250 |
+
"decoder.block.3.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 251 |
+
"decoder.block.3.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 252 |
+
"decoder.block.3.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 253 |
+
"decoder.block.3.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 254 |
+
"decoder.block.3.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 255 |
+
"decoder.block.3.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 256 |
+
"decoder.block.3.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 257 |
+
"decoder.block.3.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 258 |
+
"decoder.block.3.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 259 |
+
"decoder.block.4.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 260 |
+
"decoder.block.4.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 261 |
+
"decoder.block.4.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 262 |
+
"decoder.block.4.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 263 |
+
"decoder.block.4.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 264 |
+
"decoder.block.4.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 265 |
+
"decoder.block.4.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 266 |
+
"decoder.block.4.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 267 |
+
"decoder.block.4.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 268 |
+
"decoder.block.4.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 269 |
+
"decoder.block.4.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 270 |
+
"decoder.block.4.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 271 |
+
"decoder.block.4.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 272 |
+
"decoder.block.4.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 273 |
+
"decoder.block.5.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 274 |
+
"decoder.block.5.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 275 |
+
"decoder.block.5.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 276 |
+
"decoder.block.5.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 277 |
+
"decoder.block.5.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 278 |
+
"decoder.block.5.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 279 |
+
"decoder.block.5.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 280 |
+
"decoder.block.5.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 281 |
+
"decoder.block.5.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 282 |
+
"decoder.block.5.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 283 |
+
"decoder.block.5.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 284 |
+
"decoder.block.5.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 285 |
+
"decoder.block.5.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 286 |
+
"decoder.block.5.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 287 |
+
"decoder.block.6.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 288 |
+
"decoder.block.6.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 289 |
+
"decoder.block.6.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 290 |
+
"decoder.block.6.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 291 |
+
"decoder.block.6.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 292 |
+
"decoder.block.6.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 293 |
+
"decoder.block.6.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 294 |
+
"decoder.block.6.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 295 |
+
"decoder.block.6.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 296 |
+
"decoder.block.6.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 297 |
+
"decoder.block.6.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 298 |
+
"decoder.block.6.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 299 |
+
"decoder.block.6.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 300 |
+
"decoder.block.6.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 301 |
+
"decoder.block.7.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 302 |
+
"decoder.block.7.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 303 |
+
"decoder.block.7.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 304 |
+
"decoder.block.7.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 305 |
+
"decoder.block.7.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 306 |
+
"decoder.block.7.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 307 |
+
"decoder.block.7.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 308 |
+
"decoder.block.7.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 309 |
+
"decoder.block.7.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 310 |
+
"decoder.block.7.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 311 |
+
"decoder.block.7.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 312 |
+
"decoder.block.7.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 313 |
+
"decoder.block.7.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 314 |
+
"decoder.block.7.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 315 |
+
"decoder.block.8.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 316 |
+
"decoder.block.8.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 317 |
+
"decoder.block.8.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 318 |
+
"decoder.block.8.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 319 |
+
"decoder.block.8.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 320 |
+
"decoder.block.8.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 321 |
+
"decoder.block.8.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 322 |
+
"decoder.block.8.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 323 |
+
"decoder.block.8.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 324 |
+
"decoder.block.8.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 325 |
+
"decoder.block.8.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 326 |
+
"decoder.block.8.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 327 |
+
"decoder.block.8.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 328 |
+
"decoder.block.8.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 329 |
+
"decoder.block.9.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 330 |
+
"decoder.block.9.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 331 |
+
"decoder.block.9.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 332 |
+
"decoder.block.9.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 333 |
+
"decoder.block.9.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 334 |
+
"decoder.block.9.layer.1.EncDecAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 335 |
+
"decoder.block.9.layer.1.EncDecAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 336 |
+
"decoder.block.9.layer.1.EncDecAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 337 |
+
"decoder.block.9.layer.1.EncDecAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 338 |
+
"decoder.block.9.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 339 |
+
"decoder.block.9.layer.2.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 340 |
+
"decoder.block.9.layer.2.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 341 |
+
"decoder.block.9.layer.2.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 342 |
+
"decoder.block.9.layer.2.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 343 |
+
"decoder.embed_tokens.weight": "model-00001-of-00002.safetensors",
|
| 344 |
+
"decoder.final_layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 345 |
+
"encoder.block.0.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 346 |
+
"encoder.block.0.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 347 |
+
"encoder.block.0.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 348 |
+
"encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight": "model-00001-of-00002.safetensors",
|
| 349 |
+
"encoder.block.0.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 350 |
+
"encoder.block.0.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 351 |
+
"encoder.block.0.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 352 |
+
"encoder.block.0.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 353 |
+
"encoder.block.0.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 354 |
+
"encoder.block.0.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 355 |
+
"encoder.block.1.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 356 |
+
"encoder.block.1.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 357 |
+
"encoder.block.1.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 358 |
+
"encoder.block.1.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 359 |
+
"encoder.block.1.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 360 |
+
"encoder.block.1.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 361 |
+
"encoder.block.1.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 362 |
+
"encoder.block.1.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 363 |
+
"encoder.block.1.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 364 |
+
"encoder.block.10.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 365 |
+
"encoder.block.10.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 366 |
+
"encoder.block.10.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 367 |
+
"encoder.block.10.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 368 |
+
"encoder.block.10.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 369 |
+
"encoder.block.10.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 370 |
+
"encoder.block.10.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 371 |
+
"encoder.block.10.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 372 |
+
"encoder.block.10.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 373 |
+
"encoder.block.11.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 374 |
+
"encoder.block.11.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 375 |
+
"encoder.block.11.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 376 |
+
"encoder.block.11.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 377 |
+
"encoder.block.11.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 378 |
+
"encoder.block.11.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 379 |
+
"encoder.block.11.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 380 |
+
"encoder.block.11.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 381 |
+
"encoder.block.11.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 382 |
+
"encoder.block.12.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 383 |
+
"encoder.block.12.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 384 |
+
"encoder.block.12.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 385 |
+
"encoder.block.12.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 386 |
+
"encoder.block.12.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 387 |
+
"encoder.block.12.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 388 |
+
"encoder.block.12.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 389 |
+
"encoder.block.12.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 390 |
+
"encoder.block.12.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 391 |
+
"encoder.block.13.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 392 |
+
"encoder.block.13.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 393 |
+
"encoder.block.13.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 394 |
+
"encoder.block.13.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 395 |
+
"encoder.block.13.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 396 |
+
"encoder.block.13.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 397 |
+
"encoder.block.13.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 398 |
+
"encoder.block.13.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 399 |
+
"encoder.block.13.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 400 |
+
"encoder.block.14.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 401 |
+
"encoder.block.14.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 402 |
+
"encoder.block.14.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 403 |
+
"encoder.block.14.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 404 |
+
"encoder.block.14.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 405 |
+
"encoder.block.14.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 406 |
+
"encoder.block.14.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 407 |
+
"encoder.block.14.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 408 |
+
"encoder.block.14.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 409 |
+
"encoder.block.15.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 410 |
+
"encoder.block.15.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 411 |
+
"encoder.block.15.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 412 |
+
"encoder.block.15.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 413 |
+
"encoder.block.15.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 414 |
+
"encoder.block.15.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 415 |
+
"encoder.block.15.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 416 |
+
"encoder.block.15.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 417 |
+
"encoder.block.15.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 418 |
+
"encoder.block.16.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 419 |
+
"encoder.block.16.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 420 |
+
"encoder.block.16.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 421 |
+
"encoder.block.16.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 422 |
+
"encoder.block.16.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 423 |
+
"encoder.block.16.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 424 |
+
"encoder.block.16.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 425 |
+
"encoder.block.16.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 426 |
+
"encoder.block.16.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 427 |
+
"encoder.block.17.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 428 |
+
"encoder.block.17.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 429 |
+
"encoder.block.17.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 430 |
+
"encoder.block.17.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 431 |
+
"encoder.block.17.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 432 |
+
"encoder.block.17.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 433 |
+
"encoder.block.17.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 434 |
+
"encoder.block.17.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 435 |
+
"encoder.block.17.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 436 |
+
"encoder.block.18.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 437 |
+
"encoder.block.18.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 438 |
+
"encoder.block.18.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 439 |
+
"encoder.block.18.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 440 |
+
"encoder.block.18.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 441 |
+
"encoder.block.18.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 442 |
+
"encoder.block.18.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 443 |
+
"encoder.block.18.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 444 |
+
"encoder.block.18.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 445 |
+
"encoder.block.19.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 446 |
+
"encoder.block.19.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 447 |
+
"encoder.block.19.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 448 |
+
"encoder.block.19.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 449 |
+
"encoder.block.19.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 450 |
+
"encoder.block.19.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 451 |
+
"encoder.block.19.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 452 |
+
"encoder.block.19.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 453 |
+
"encoder.block.19.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 454 |
+
"encoder.block.2.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 455 |
+
"encoder.block.2.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 456 |
+
"encoder.block.2.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 457 |
+
"encoder.block.2.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 458 |
+
"encoder.block.2.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 459 |
+
"encoder.block.2.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 460 |
+
"encoder.block.2.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 461 |
+
"encoder.block.2.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 462 |
+
"encoder.block.2.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 463 |
+
"encoder.block.20.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 464 |
+
"encoder.block.20.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 465 |
+
"encoder.block.20.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 466 |
+
"encoder.block.20.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 467 |
+
"encoder.block.20.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 468 |
+
"encoder.block.20.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 469 |
+
"encoder.block.20.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 470 |
+
"encoder.block.20.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 471 |
+
"encoder.block.20.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 472 |
+
"encoder.block.21.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 473 |
+
"encoder.block.21.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 474 |
+
"encoder.block.21.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 475 |
+
"encoder.block.21.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 476 |
+
"encoder.block.21.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 477 |
+
"encoder.block.21.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 478 |
+
"encoder.block.21.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 479 |
+
"encoder.block.21.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 480 |
+
"encoder.block.21.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 481 |
+
"encoder.block.22.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 482 |
+
"encoder.block.22.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 483 |
+
"encoder.block.22.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 484 |
+
"encoder.block.22.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 485 |
+
"encoder.block.22.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 486 |
+
"encoder.block.22.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 487 |
+
"encoder.block.22.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 488 |
+
"encoder.block.22.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 489 |
+
"encoder.block.22.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 490 |
+
"encoder.block.23.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 491 |
+
"encoder.block.23.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 492 |
+
"encoder.block.23.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 493 |
+
"encoder.block.23.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 494 |
+
"encoder.block.23.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 495 |
+
"encoder.block.23.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 496 |
+
"encoder.block.23.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 497 |
+
"encoder.block.23.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 498 |
+
"encoder.block.23.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 499 |
+
"encoder.block.24.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 500 |
+
"encoder.block.24.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 501 |
+
"encoder.block.24.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 502 |
+
"encoder.block.24.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 503 |
+
"encoder.block.24.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 504 |
+
"encoder.block.24.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 505 |
+
"encoder.block.24.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 506 |
+
"encoder.block.24.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 507 |
+
"encoder.block.24.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 508 |
+
"encoder.block.25.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 509 |
+
"encoder.block.25.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 510 |
+
"encoder.block.25.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 511 |
+
"encoder.block.25.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 512 |
+
"encoder.block.25.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 513 |
+
"encoder.block.25.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 514 |
+
"encoder.block.25.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 515 |
+
"encoder.block.25.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 516 |
+
"encoder.block.25.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 517 |
+
"encoder.block.26.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 518 |
+
"encoder.block.26.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 519 |
+
"encoder.block.26.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 520 |
+
"encoder.block.26.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 521 |
+
"encoder.block.26.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 522 |
+
"encoder.block.26.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 523 |
+
"encoder.block.26.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 524 |
+
"encoder.block.26.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 525 |
+
"encoder.block.26.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 526 |
+
"encoder.block.27.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 527 |
+
"encoder.block.27.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 528 |
+
"encoder.block.27.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 529 |
+
"encoder.block.27.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 530 |
+
"encoder.block.27.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 531 |
+
"encoder.block.27.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 532 |
+
"encoder.block.27.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 533 |
+
"encoder.block.27.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 534 |
+
"encoder.block.27.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 535 |
+
"encoder.block.28.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 536 |
+
"encoder.block.28.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 537 |
+
"encoder.block.28.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 538 |
+
"encoder.block.28.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 539 |
+
"encoder.block.28.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 540 |
+
"encoder.block.28.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 541 |
+
"encoder.block.28.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 542 |
+
"encoder.block.28.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 543 |
+
"encoder.block.28.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 544 |
+
"encoder.block.29.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 545 |
+
"encoder.block.29.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 546 |
+
"encoder.block.29.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 547 |
+
"encoder.block.29.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 548 |
+
"encoder.block.29.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 549 |
+
"encoder.block.29.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 550 |
+
"encoder.block.29.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 551 |
+
"encoder.block.29.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 552 |
+
"encoder.block.29.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 553 |
+
"encoder.block.3.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 554 |
+
"encoder.block.3.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 555 |
+
"encoder.block.3.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 556 |
+
"encoder.block.3.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 557 |
+
"encoder.block.3.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 558 |
+
"encoder.block.3.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 559 |
+
"encoder.block.3.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 560 |
+
"encoder.block.3.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 561 |
+
"encoder.block.3.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 562 |
+
"encoder.block.30.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 563 |
+
"encoder.block.30.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 564 |
+
"encoder.block.30.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 565 |
+
"encoder.block.30.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 566 |
+
"encoder.block.30.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 567 |
+
"encoder.block.30.layer.1.DenseReluDense.wi_0.weight": "model-00001-of-00002.safetensors",
|
| 568 |
+
"encoder.block.30.layer.1.DenseReluDense.wi_1.weight": "model-00001-of-00002.safetensors",
|
| 569 |
+
"encoder.block.30.layer.1.DenseReluDense.wo.weight": "model-00001-of-00002.safetensors",
|
| 570 |
+
"encoder.block.30.layer.1.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 571 |
+
"encoder.block.31.layer.0.SelfAttention.k.weight": "model-00001-of-00002.safetensors",
|
| 572 |
+
"encoder.block.31.layer.0.SelfAttention.o.weight": "model-00001-of-00002.safetensors",
|
| 573 |
+
"encoder.block.31.layer.0.SelfAttention.q.weight": "model-00001-of-00002.safetensors",
|
| 574 |
+
"encoder.block.31.layer.0.SelfAttention.v.weight": "model-00001-of-00002.safetensors",
|
| 575 |
+
"encoder.block.31.layer.0.layer_norm.weight": "model-00001-of-00002.safetensors",
|
| 576 |
+
"encoder.block.31.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 577 |
+
"encoder.block.31.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 578 |
+
"encoder.block.31.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 579 |
+
"encoder.block.31.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 580 |
+
"encoder.block.32.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 581 |
+
"encoder.block.32.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 582 |
+
"encoder.block.32.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 583 |
+
"encoder.block.32.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 584 |
+
"encoder.block.32.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 585 |
+
"encoder.block.32.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 586 |
+
"encoder.block.32.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 587 |
+
"encoder.block.32.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 588 |
+
"encoder.block.32.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 589 |
+
"encoder.block.33.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 590 |
+
"encoder.block.33.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 591 |
+
"encoder.block.33.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 592 |
+
"encoder.block.33.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 593 |
+
"encoder.block.33.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 594 |
+
"encoder.block.33.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 595 |
+
"encoder.block.33.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 596 |
+
"encoder.block.33.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 597 |
+
"encoder.block.33.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 598 |
+
"encoder.block.34.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 599 |
+
"encoder.block.34.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 600 |
+
"encoder.block.34.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 601 |
+
"encoder.block.34.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 602 |
+
"encoder.block.34.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 603 |
+
"encoder.block.34.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 604 |
+
"encoder.block.34.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 605 |
+
"encoder.block.34.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 606 |
+
"encoder.block.34.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 607 |
+
"encoder.block.35.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 608 |
+
"encoder.block.35.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 609 |
+
"encoder.block.35.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 610 |
+
"encoder.block.35.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 611 |
+
"encoder.block.35.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 612 |
+
"encoder.block.35.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 613 |
+
"encoder.block.35.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 614 |
+
"encoder.block.35.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 615 |
+
"encoder.block.35.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 616 |
+
"encoder.block.36.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 617 |
+
"encoder.block.36.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 618 |
+
"encoder.block.36.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 619 |
+
"encoder.block.36.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 620 |
+
"encoder.block.36.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 621 |
+
"encoder.block.36.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 622 |
+
"encoder.block.36.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 623 |
+
"encoder.block.36.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 624 |
+
"encoder.block.36.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 625 |
+
"encoder.block.37.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 626 |
+
"encoder.block.37.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 627 |
+
"encoder.block.37.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 628 |
+
"encoder.block.37.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 629 |
+
"encoder.block.37.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 630 |
+
"encoder.block.37.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 631 |
+
"encoder.block.37.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 632 |
+
"encoder.block.37.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 633 |
+
"encoder.block.37.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 634 |
+
"encoder.block.38.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 635 |
+
"encoder.block.38.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 636 |
+
"encoder.block.38.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 637 |
+
"encoder.block.38.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 638 |
+
"encoder.block.38.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 639 |
+
"encoder.block.38.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 640 |
+
"encoder.block.38.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 641 |
+
"encoder.block.38.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 642 |
+
"encoder.block.38.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 643 |
+
"encoder.block.39.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 644 |
+
"encoder.block.39.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 645 |
+
"encoder.block.39.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 646 |
+
"encoder.block.39.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 647 |
+
"encoder.block.39.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 648 |
+
"encoder.block.39.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 649 |
+
"encoder.block.39.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 650 |
+
"encoder.block.39.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 651 |
+
"encoder.block.39.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 652 |
+
"encoder.block.4.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 653 |
+
"encoder.block.4.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 654 |
+
"encoder.block.4.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 655 |
+
"encoder.block.4.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 656 |
+
"encoder.block.4.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 657 |
+
"encoder.block.4.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 658 |
+
"encoder.block.4.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 659 |
+
"encoder.block.4.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 660 |
+
"encoder.block.4.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 661 |
+
"encoder.block.40.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 662 |
+
"encoder.block.40.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 663 |
+
"encoder.block.40.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 664 |
+
"encoder.block.40.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 665 |
+
"encoder.block.40.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 666 |
+
"encoder.block.40.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 667 |
+
"encoder.block.40.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 668 |
+
"encoder.block.40.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 669 |
+
"encoder.block.40.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 670 |
+
"encoder.block.41.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 671 |
+
"encoder.block.41.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 672 |
+
"encoder.block.41.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 673 |
+
"encoder.block.41.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 674 |
+
"encoder.block.41.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 675 |
+
"encoder.block.41.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 676 |
+
"encoder.block.41.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 677 |
+
"encoder.block.41.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 678 |
+
"encoder.block.41.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 679 |
+
"encoder.block.42.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 680 |
+
"encoder.block.42.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 681 |
+
"encoder.block.42.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 682 |
+
"encoder.block.42.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 683 |
+
"encoder.block.42.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 684 |
+
"encoder.block.42.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 685 |
+
"encoder.block.42.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 686 |
+
"encoder.block.42.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 687 |
+
"encoder.block.42.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 688 |
+
"encoder.block.43.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 689 |
+
"encoder.block.43.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 690 |
+
"encoder.block.43.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 691 |
+
"encoder.block.43.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 692 |
+
"encoder.block.43.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 693 |
+
"encoder.block.43.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 694 |
+
"encoder.block.43.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 695 |
+
"encoder.block.43.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 696 |
+
"encoder.block.43.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 697 |
+
"encoder.block.44.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 698 |
+
"encoder.block.44.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 699 |
+
"encoder.block.44.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 700 |
+
"encoder.block.44.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 701 |
+
"encoder.block.44.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 702 |
+
"encoder.block.44.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 703 |
+
"encoder.block.44.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 704 |
+
"encoder.block.44.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 705 |
+
"encoder.block.44.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 706 |
+
"encoder.block.45.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 707 |
+
"encoder.block.45.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 708 |
+
"encoder.block.45.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 709 |
+
"encoder.block.45.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 710 |
+
"encoder.block.45.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 711 |
+
"encoder.block.45.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 712 |
+
"encoder.block.45.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 713 |
+
"encoder.block.45.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 714 |
+
"encoder.block.45.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 715 |
+
"encoder.block.46.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 716 |
+
"encoder.block.46.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 717 |
+
"encoder.block.46.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 718 |
+
"encoder.block.46.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 719 |
+
"encoder.block.46.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 720 |
+
"encoder.block.46.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 721 |
+
"encoder.block.46.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 722 |
+
"encoder.block.46.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 723 |
+
"encoder.block.46.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 724 |
+
"encoder.block.47.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 725 |
+
"encoder.block.47.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 726 |
+
"encoder.block.47.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 727 |
+
"encoder.block.47.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 728 |
+
"encoder.block.47.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 729 |
+
"encoder.block.47.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 730 |
+
"encoder.block.47.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 731 |
+
"encoder.block.47.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 732 |
+
"encoder.block.47.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 733 |
+
"encoder.block.5.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 734 |
+
"encoder.block.5.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 735 |
+
"encoder.block.5.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 736 |
+
"encoder.block.5.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 737 |
+
"encoder.block.5.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 738 |
+
"encoder.block.5.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 739 |
+
"encoder.block.5.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 740 |
+
"encoder.block.5.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 741 |
+
"encoder.block.5.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 742 |
+
"encoder.block.6.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 743 |
+
"encoder.block.6.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 744 |
+
"encoder.block.6.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 745 |
+
"encoder.block.6.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 746 |
+
"encoder.block.6.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 747 |
+
"encoder.block.6.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 748 |
+
"encoder.block.6.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 749 |
+
"encoder.block.6.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 750 |
+
"encoder.block.6.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 751 |
+
"encoder.block.7.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 752 |
+
"encoder.block.7.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 753 |
+
"encoder.block.7.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 754 |
+
"encoder.block.7.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 755 |
+
"encoder.block.7.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 756 |
+
"encoder.block.7.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 757 |
+
"encoder.block.7.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 758 |
+
"encoder.block.7.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 759 |
+
"encoder.block.7.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 760 |
+
"encoder.block.8.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 761 |
+
"encoder.block.8.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 762 |
+
"encoder.block.8.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 763 |
+
"encoder.block.8.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 764 |
+
"encoder.block.8.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 765 |
+
"encoder.block.8.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 766 |
+
"encoder.block.8.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 767 |
+
"encoder.block.8.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 768 |
+
"encoder.block.8.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 769 |
+
"encoder.block.9.layer.0.SelfAttention.k.weight": "model-00002-of-00002.safetensors",
|
| 770 |
+
"encoder.block.9.layer.0.SelfAttention.o.weight": "model-00002-of-00002.safetensors",
|
| 771 |
+
"encoder.block.9.layer.0.SelfAttention.q.weight": "model-00002-of-00002.safetensors",
|
| 772 |
+
"encoder.block.9.layer.0.SelfAttention.v.weight": "model-00002-of-00002.safetensors",
|
| 773 |
+
"encoder.block.9.layer.0.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 774 |
+
"encoder.block.9.layer.1.DenseReluDense.wi_0.weight": "model-00002-of-00002.safetensors",
|
| 775 |
+
"encoder.block.9.layer.1.DenseReluDense.wi_1.weight": "model-00002-of-00002.safetensors",
|
| 776 |
+
"encoder.block.9.layer.1.DenseReluDense.wo.weight": "model-00002-of-00002.safetensors",
|
| 777 |
+
"encoder.block.9.layer.1.layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 778 |
+
"encoder.embed_tokens.weight": "model-00002-of-00002.safetensors",
|
| 779 |
+
"encoder.final_layer_norm.weight": "model-00002-of-00002.safetensors",
|
| 780 |
+
"lm_head.weight": "model-00002-of-00002.safetensors",
|
| 781 |
+
"shared.weight": "model-00002-of-00002.safetensors"
|
| 782 |
+
}
|
| 783 |
+
}
|
modeling_fastplms.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
"""Generated bridge to the unchanged FastPLMs package sources."""
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import hashlib
|
| 5 |
+
import importlib
|
| 6 |
+
import importlib.util
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
from importlib.metadata import PackageNotFoundError, distribution
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from zipfile import ZIP_DEFLATED, ZipFile
|
| 13 |
+
|
| 14 |
+
from .fastplms_bundle import RUNTIME_DATA, RUNTIME_HASH
|
| 15 |
+
|
| 16 |
+
if RUNTIME_HASH != "17b8f83a33e63d941e3edfb8db2d8381286046b572f94194e576ca394d997597":
|
| 17 |
+
raise RuntimeError("FastPLMs runtime identity differs from the bridge.")
|
| 18 |
+
|
| 19 |
+
_RUNTIME_TEMPORARIES = []
|
| 20 |
+
|
| 21 |
+
def _archive_runtime_hashes(payload):
|
| 22 |
+
result = {}
|
| 23 |
+
with ZipFile(BytesIO(payload)) as archive:
|
| 24 |
+
for member in archive.infolist():
|
| 25 |
+
name = member.filename
|
| 26 |
+
parts = Path(name).parts
|
| 27 |
+
if (
|
| 28 |
+
member.is_dir()
|
| 29 |
+
or "\\" in name
|
| 30 |
+
or not parts
|
| 31 |
+
or parts[0] != "fastplms"
|
| 32 |
+
or len(parts) < 2
|
| 33 |
+
or any(part in {"", ".", ".."} for part in parts)
|
| 34 |
+
or Path(name).suffix in {".pyc", ".pyo"}
|
| 35 |
+
or member.flag_bits & 0x1
|
| 36 |
+
or member.compress_type != ZIP_DEFLATED
|
| 37 |
+
or member.external_attr >> 16 != 0o100644
|
| 38 |
+
):
|
| 39 |
+
raise RuntimeError("Embedded FastPLMs archive has an unsafe path.")
|
| 40 |
+
relative = Path(*parts[1:]).as_posix()
|
| 41 |
+
if relative in result:
|
| 42 |
+
raise RuntimeError("Embedded FastPLMs archive repeats a path.")
|
| 43 |
+
result[relative] = hashlib.sha256(archive.read(member)).hexdigest()
|
| 44 |
+
return result
|
| 45 |
+
|
| 46 |
+
def _ensure_runtime():
|
| 47 |
+
payload = base64.b85decode("".join(RUNTIME_DATA))
|
| 48 |
+
if hashlib.sha256(payload).hexdigest() != RUNTIME_HASH:
|
| 49 |
+
raise RuntimeError("Embedded FastPLMs runtime hash mismatch.")
|
| 50 |
+
expected = _archive_runtime_hashes(payload)
|
| 51 |
+
temporary = tempfile.TemporaryDirectory(prefix="fastplms-artifact-runtime-")
|
| 52 |
+
try:
|
| 53 |
+
runtime_root = Path(temporary.name)
|
| 54 |
+
with ZipFile(BytesIO(payload)) as archive:
|
| 55 |
+
for member in archive.infolist():
|
| 56 |
+
target = runtime_root.joinpath(*Path(member.filename).parts)
|
| 57 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
with target.open("xb") as handle:
|
| 59 |
+
handle.write(archive.read(member))
|
| 60 |
+
package_root = runtime_root / "fastplms"
|
| 61 |
+
if _runtime_file_hashes(package_root) != expected:
|
| 62 |
+
raise RuntimeError(
|
| 63 |
+
"Private FastPLMs runtime differs from the embedded archive."
|
| 64 |
+
)
|
| 65 |
+
except BaseException:
|
| 66 |
+
temporary.cleanup()
|
| 67 |
+
raise
|
| 68 |
+
_RUNTIME_TEMPORARIES.append(temporary)
|
| 69 |
+
return package_root
|
| 70 |
+
|
| 71 |
+
def _runtime_file_hashes(package_root):
|
| 72 |
+
result = {}
|
| 73 |
+
for path in sorted(package_root.rglob("*")):
|
| 74 |
+
relative = path.relative_to(package_root)
|
| 75 |
+
if path.is_symlink():
|
| 76 |
+
raise RuntimeError("Private FastPLMs runtime contains a symlink.")
|
| 77 |
+
if path.is_dir():
|
| 78 |
+
continue
|
| 79 |
+
if path.suffix in {".pyc", ".pyo"}:
|
| 80 |
+
raise RuntimeError("Private FastPLMs runtime contains bytecode.")
|
| 81 |
+
if not path.is_file():
|
| 82 |
+
raise RuntimeError("Private FastPLMs runtime contains a non-file entry.")
|
| 83 |
+
result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
|
| 84 |
+
return result
|
| 85 |
+
|
| 86 |
+
def _installed_runtime_digest(installed_root, relative):
|
| 87 |
+
candidate = installed_root / relative
|
| 88 |
+
if candidate.is_file():
|
| 89 |
+
return hashlib.sha256(candidate.read_bytes()).hexdigest()
|
| 90 |
+
if relative != "kernels.lock":
|
| 91 |
+
return None
|
| 92 |
+
try:
|
| 93 |
+
installed_distribution = distribution("fastplms")
|
| 94 |
+
except PackageNotFoundError:
|
| 95 |
+
return None
|
| 96 |
+
for entry in installed_distribution.files or ():
|
| 97 |
+
normalized = str(entry).replace("\\", "/")
|
| 98 |
+
if normalized.endswith(".dist-info/kernels.lock"):
|
| 99 |
+
lock_path = Path(installed_distribution.locate_file(entry))
|
| 100 |
+
if lock_path.is_file():
|
| 101 |
+
return hashlib.sha256(lock_path.read_bytes()).hexdigest()
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
def _extend_loaded_package_paths(package_root):
|
| 105 |
+
for name, module in list(sys.modules.items()):
|
| 106 |
+
if name != "fastplms" and not name.startswith("fastplms."):
|
| 107 |
+
continue
|
| 108 |
+
paths = getattr(module, "__path__", None)
|
| 109 |
+
if paths is None:
|
| 110 |
+
continue
|
| 111 |
+
relative = name.split(".")[1:]
|
| 112 |
+
candidate = package_root.joinpath(*relative)
|
| 113 |
+
candidate_text = str(candidate)
|
| 114 |
+
if candidate.is_dir() and candidate_text not in paths:
|
| 115 |
+
paths.append(candidate_text)
|
| 116 |
+
|
| 117 |
+
def _merge_runtime(installed, package_root):
|
| 118 |
+
incoming = _runtime_file_hashes(package_root)
|
| 119 |
+
known = dict(getattr(installed, "__fastplms_artifact_runtime_files__", {}))
|
| 120 |
+
installed_root_text = getattr(
|
| 121 |
+
installed, "__fastplms_artifact_installed_root__", None
|
| 122 |
+
)
|
| 123 |
+
if not known:
|
| 124 |
+
installed_file = getattr(installed, "__file__", None)
|
| 125 |
+
if installed_file is None:
|
| 126 |
+
raise RuntimeError(
|
| 127 |
+
"The loaded fastplms package has no source path and cannot be verified "
|
| 128 |
+
"against the embedded artifact runtime."
|
| 129 |
+
)
|
| 130 |
+
installed_root = Path(installed_file).resolve().parent
|
| 131 |
+
for relative, digest in incoming.items():
|
| 132 |
+
if _installed_runtime_digest(installed_root, relative) != digest:
|
| 133 |
+
raise RuntimeError(
|
| 134 |
+
"The installed FastPLMs runtime differs from this artifact at "
|
| 135 |
+
f"{relative!r}. Install the artifact's matching FastPLMs release "
|
| 136 |
+
"or use a separate Python process."
|
| 137 |
+
)
|
| 138 |
+
installed_root_text = str(installed_root)
|
| 139 |
+
installed.__fastplms_artifact_installed_root__ = installed_root_text
|
| 140 |
+
conflicts = sorted(
|
| 141 |
+
relative
|
| 142 |
+
for relative, digest in incoming.items()
|
| 143 |
+
if relative in known and known[relative] != digest
|
| 144 |
+
)
|
| 145 |
+
if conflicts:
|
| 146 |
+
raise RuntimeError(
|
| 147 |
+
"FastPLMs artifacts contain incompatible runtime sources at "
|
| 148 |
+
+ ", ".join(repr(path) for path in conflicts[:5])
|
| 149 |
+
+ ". Load incompatible releases in separate Python processes."
|
| 150 |
+
)
|
| 151 |
+
if installed_root_text is not None:
|
| 152 |
+
installed_root = Path(installed_root_text)
|
| 153 |
+
for relative, digest in incoming.items():
|
| 154 |
+
if relative in known:
|
| 155 |
+
continue
|
| 156 |
+
if _installed_runtime_digest(installed_root, relative) != digest:
|
| 157 |
+
raise RuntimeError(
|
| 158 |
+
"The installed FastPLMs runtime differs from this artifact at "
|
| 159 |
+
f"{relative!r}. Install the artifact's matching FastPLMs release "
|
| 160 |
+
"or use a separate Python process."
|
| 161 |
+
)
|
| 162 |
+
known.update(incoming)
|
| 163 |
+
installed.__fastplms_artifact_runtime_files__ = known
|
| 164 |
+
roots = list(getattr(installed, "__fastplms_artifact_runtime_roots__", ()))
|
| 165 |
+
if str(package_root) not in roots:
|
| 166 |
+
roots.append(str(package_root))
|
| 167 |
+
installed.__fastplms_artifact_runtime_roots__ = tuple(roots)
|
| 168 |
+
temporaries = list(
|
| 169 |
+
getattr(installed, "__fastplms_artifact_runtime_temporaries__", ())
|
| 170 |
+
)
|
| 171 |
+
for temporary in _RUNTIME_TEMPORARIES:
|
| 172 |
+
if temporary not in temporaries:
|
| 173 |
+
temporaries.append(temporary)
|
| 174 |
+
installed.__fastplms_artifact_runtime_temporaries__ = tuple(temporaries)
|
| 175 |
+
hashes = set(getattr(installed, "__fastplms_artifact_runtime_hashes__", ()))
|
| 176 |
+
hashes.add(RUNTIME_HASH)
|
| 177 |
+
installed.__fastplms_artifact_runtime_hashes__ = frozenset(hashes)
|
| 178 |
+
_extend_loaded_package_paths(package_root)
|
| 179 |
+
return installed
|
| 180 |
+
|
| 181 |
+
def _import_without_bytecode(module_name):
|
| 182 |
+
previous = sys.dont_write_bytecode
|
| 183 |
+
sys.dont_write_bytecode = True
|
| 184 |
+
try:
|
| 185 |
+
return importlib.import_module(module_name)
|
| 186 |
+
finally:
|
| 187 |
+
sys.dont_write_bytecode = previous
|
| 188 |
+
|
| 189 |
+
def _install_runtime():
|
| 190 |
+
installed = sys.modules.get("fastplms")
|
| 191 |
+
hashes = getattr(installed, "__fastplms_artifact_runtime_hashes__", ())
|
| 192 |
+
if RUNTIME_HASH in hashes:
|
| 193 |
+
return installed
|
| 194 |
+
package_root = _ensure_runtime()
|
| 195 |
+
if installed is not None:
|
| 196 |
+
return _merge_runtime(installed, package_root)
|
| 197 |
+
spec = importlib.util.spec_from_file_location(
|
| 198 |
+
"fastplms",
|
| 199 |
+
package_root / "__init__.py",
|
| 200 |
+
submodule_search_locations=[str(package_root)],
|
| 201 |
+
)
|
| 202 |
+
if spec is None or spec.loader is None:
|
| 203 |
+
raise ImportError("Unable to load the embedded FastPLMs runtime.")
|
| 204 |
+
package = importlib.util.module_from_spec(spec)
|
| 205 |
+
package.__fastplms_artifact_runtime_hash__ = RUNTIME_HASH
|
| 206 |
+
package.__fastplms_artifact_runtime_hashes__ = frozenset({RUNTIME_HASH})
|
| 207 |
+
package.__fastplms_artifact_runtime_files__ = _runtime_file_hashes(package_root)
|
| 208 |
+
package.__fastplms_artifact_runtime_roots__ = (str(package_root),)
|
| 209 |
+
package.__fastplms_artifact_runtime_temporaries__ = tuple(
|
| 210 |
+
_RUNTIME_TEMPORARIES
|
| 211 |
+
)
|
| 212 |
+
sys.modules["fastplms"] = package
|
| 213 |
+
previous = sys.dont_write_bytecode
|
| 214 |
+
sys.dont_write_bytecode = True
|
| 215 |
+
try:
|
| 216 |
+
try:
|
| 217 |
+
spec.loader.exec_module(package)
|
| 218 |
+
except BaseException:
|
| 219 |
+
sys.modules.pop("fastplms", None)
|
| 220 |
+
raise
|
| 221 |
+
finally:
|
| 222 |
+
sys.dont_write_bytecode = previous
|
| 223 |
+
return package
|
| 224 |
+
|
| 225 |
+
_install_runtime()
|
| 226 |
+
_module_225 = _import_without_bytecode("fastplms.models.ankh.modeling_ankh")
|
| 227 |
+
FastAnkhConfig = _module_225.FastAnkhConfig
|
| 228 |
+
FastAnkhConfig.__module__ = __name__
|
| 229 |
+
FastAnkhForConditionalGeneration = _module_225.FastAnkhForConditionalGeneration
|
| 230 |
+
FastAnkhForConditionalGeneration.__module__ = __name__
|
| 231 |
+
FastAnkhForMaskedLMExtension = _module_225.FastAnkhForMaskedLMExtension
|
| 232 |
+
FastAnkhForMaskedLMExtension.__module__ = __name__
|
| 233 |
+
FastAnkhForSequenceClassification = _module_225.FastAnkhForSequenceClassification
|
| 234 |
+
FastAnkhForSequenceClassification.__module__ = __name__
|
| 235 |
+
FastAnkhForTokenClassification = _module_225.FastAnkhForTokenClassification
|
| 236 |
+
FastAnkhForTokenClassification.__module__ = __name__
|
| 237 |
+
FastAnkhModel = _module_225.FastAnkhModel
|
| 238 |
+
FastAnkhModel.__module__ = __name__
|
provenance.json
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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sha1:9286bed4ecbc4f7113024919d16ec9719b0c0748",
|
| 6 |
+
"generation_config.json": "git-sha1:91f792e452403d46e170e206f9e50be5ddef9b9a",
|
| 7 |
+
"pytorch_model.bin": "sha256:2df583f28f111276ee22a7b76007f4297e9a69766d60bccd9c8d7169c06ac606",
|
| 8 |
+
"special_tokens_map.json": "git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 9 |
+
"tokenizer.json": "git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 10 |
+
"tokenizer_config.json": "git-sha1:854e5db75dae8b1e9dd39c5bae80dae5508b3e25"
|
| 11 |
+
},
|
| 12 |
+
"repo_id": "ElnaggarLab/ankh2-ext2",
|
| 13 |
+
"revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8",
|
| 14 |
+
"unresolved_files": []
|
| 15 |
+
},
|
| 16 |
+
"artifact_source": "official",
|
| 17 |
+
"attestations": {
|
| 18 |
+
"complete_artifact": {
|
| 19 |
+
"redistributable": true,
|
| 20 |
+
"release_tool_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 21 |
+
"release_tool_sha256": "1459b5d7d13d9b07bd97b3eee764f2ce73623e15e32d07ddf6825c2a9509afb9",
|
| 22 |
+
"runtime_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 23 |
+
"scope": "weights+runtime",
|
| 24 |
+
"weights_license_status": "resolved",
|
| 25 |
+
"weights_revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8"
|
| 26 |
+
},
|
| 27 |
+
"runtime_update": {
|
| 28 |
+
"path": "runtime-attestation.json",
|
| 29 |
+
"redistributable": true,
|
| 30 |
+
"release_tool_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 31 |
+
"release_tool_sha256": "1459b5d7d13d9b07bd97b3eee764f2ce73623e15e32d07ddf6825c2a9509afb9",
|
| 32 |
+
"scope": "runtime-only",
|
| 33 |
+
"weights_license_status": "resolved",
|
| 34 |
+
"weights_repo_id": "Synthyra/ANKH2_large",
|
| 35 |
+
"weights_revision": "392de5ed52bbfd73b45f545e378aaebcff096d0e"
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
"auto_map": {
|
| 39 |
+
"AutoConfig": "fastplms.models.ankh.modeling_ankh.FastAnkhConfig",
|
| 40 |
+
"AutoModel": "fastplms.models.ankh.modeling_ankh.FastAnkhModel",
|
| 41 |
+
"AutoModelForMaskedLM": "fastplms.models.ankh.modeling_ankh.FastAnkhForMaskedLMExtension",
|
| 42 |
+
"AutoModelForSeq2SeqLM": "fastplms.models.ankh.modeling_ankh.FastAnkhForConditionalGeneration",
|
| 43 |
+
"AutoModelForSequenceClassification": "fastplms.models.ankh.modeling_ankh.FastAnkhForSequenceClassification",
|
| 44 |
+
"AutoModelForTokenClassification": "fastplms.models.ankh.modeling_ankh.FastAnkhForTokenClassification"
|
| 45 |
+
},
|
| 46 |
+
"bf16_execution": "static_parameters",
|
| 47 |
+
"canonical_weights": {
|
| 48 |
+
"format": "safetensors",
|
| 49 |
+
"index": "model.safetensors.index.json",
|
| 50 |
+
"index_digest": "sha256:eb9f1a3b03bd5fc5dd912aa4244181ed09e19b99a57c2e1d95bdf952e510cea3",
|
| 51 |
+
"max_shard_bytes": 5368709120,
|
| 52 |
+
"shards": {
|
| 53 |
+
"model-00001-of-00002.safetensors": "sha256:7c0c297f60bcf81c732cdfeae6e99e140272807eb52afd70356fc6fdfa94e5a8",
|
| 54 |
+
"model-00002-of-00002.safetensors": "sha256:f3d425d3e8741ccbdd925446559a9bf317c2c91e328f2eee44924423b56e3a3d"
|
| 55 |
+
},
|
| 56 |
+
"source_schema": "official",
|
| 57 |
+
"state_digest": {
|
| 58 |
+
"algorithm": "sha256",
|
| 59 |
+
"schema_version": 1,
|
| 60 |
+
"sha256": "597c4fe2fa8711f11a25317905f1d62fa92905e55fdd5c0a79614cd9c9d2bca3"
|
| 61 |
+
},
|
| 62 |
+
"state_transform": "ankh_t5_to_fastplms_v1",
|
| 63 |
+
"tensor_count": 776,
|
| 64 |
+
"total_size": 7516590080
|
| 65 |
+
},
|
| 66 |
+
"checkpoint_license": "CC-BY-NC-SA-4.0",
|
| 67 |
+
"conversion": {
|
| 68 |
+
"id": "ankh_t5_to_fastplms_v1",
|
| 69 |
+
"record": "Input: the pinned official ANKH T5 checkpoint. Transformation: apply ankh_t5_to_fastplms_v1 to the official encoder and sequence-to-sequence heads. Output: the pinned Synthyra ANKH checkpoint. Validation: release parity compares exact mapped state, tokenizer behavior, official heads, and inference. Limitation: the separately named FastPLMs masked-language-model extension is not an official ANKH head."
|
| 70 |
+
},
|
| 71 |
+
"conversion_equality_attestation": {
|
| 72 |
+
"attestation_sha256": "4b5acf56ebc107b0177b873116d4a498c7da56bcf41cecce250310ad302fa075",
|
| 73 |
+
"canonical_state": {
|
| 74 |
+
"algorithm": "sha256",
|
| 75 |
+
"schema_version": 1,
|
| 76 |
+
"sha256": "597c4fe2fa8711f11a25317905f1d62fa92905e55fdd5c0a79614cd9c9d2bca3"
|
| 77 |
+
},
|
| 78 |
+
"conversion_record_sha256": "34015dc5c07465d93b54349e6ac3b68179101bb231d7bac41af308287d69dc7d",
|
| 79 |
+
"model_id": "ankh2_large",
|
| 80 |
+
"schema_version": 1,
|
| 81 |
+
"source_checkpoint": {
|
| 82 |
+
"identity_sha256": "ca31eec9942e836d0b557a94d3b50e642af3738627a348d6526a6968b8646f8c",
|
| 83 |
+
"repo_id": "ElnaggarLab/ankh2-ext2",
|
| 84 |
+
"revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8"
|
| 85 |
+
},
|
| 86 |
+
"state_transform": "ankh_t5_to_fastplms_v1"
|
| 87 |
+
},
|
| 88 |
+
"fast_checkpoint": {
|
| 89 |
+
"files": {
|
| 90 |
+
"config.json": "git-sha1:66b6adc7215743a98a3229958bbd1c9c42b6108b",
|
| 91 |
+
"model.safetensors": "sha256:be8e6242388d93b51cd9719a0e32cfc17a2e804786570c795ba332197eccb915",
|
| 92 |
+
"special_tokens_map.json": "git-sha1:a2d8d626c31389a935e197fb94072e2414a6e7d1",
|
| 93 |
+
"tokenizer.json": "git-sha1:0734d752d12d0f46ac96467fbceb1c4bfbeee0be",
|
| 94 |
+
"tokenizer_config.json": "git-sha1:db0b80de72d3b16242b9eda74ed4663e39c65bcf"
|
| 95 |
+
},
|
| 96 |
+
"repo_id": "Synthyra/ANKH2_large",
|
| 97 |
+
"revision": "392de5ed52bbfd73b45f545e378aaebcff096d0e",
|
| 98 |
+
"unresolved_files": []
|
| 99 |
+
},
|
| 100 |
+
"fastplms_version": "1.0.0",
|
| 101 |
+
"generator": {
|
| 102 |
+
"name": "tools.artifacts.build",
|
| 103 |
+
"version": 3
|
| 104 |
+
},
|
| 105 |
+
"hub_license_metadata": {
|
| 106 |
+
"license": "cc-by-nc-sa-4.0"
|
| 107 |
+
},
|
| 108 |
+
"legal_files": {
|
| 109 |
+
"LICENSE": "sha256:2d2b50c7b1414bff1189a1db1f0cfb92e3e064b50f4c2b1019827b683e1b629a",
|
| 110 |
+
"THIRD_PARTY_NOTICES.md": "sha256:25704b3c76404696cae52e7fca13088d329f70f412687340351259e86cd62baa"
|
| 111 |
+
},
|
| 112 |
+
"model_id": "ankh2_large",
|
| 113 |
+
"official_checkpoint": {
|
| 114 |
+
"files": {
|
| 115 |
+
"config.json": "git-sha1:9286bed4ecbc4f7113024919d16ec9719b0c0748",
|
| 116 |
+
"generation_config.json": "git-sha1:91f792e452403d46e170e206f9e50be5ddef9b9a",
|
| 117 |
+
"pytorch_model.bin": "sha256:2df583f28f111276ee22a7b76007f4297e9a69766d60bccd9c8d7169c06ac606",
|
| 118 |
+
"special_tokens_map.json": "git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 119 |
+
"tokenizer.json": "git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 120 |
+
"tokenizer_config.json": "git-sha1:854e5db75dae8b1e9dd39c5bae80dae5508b3e25"
|
| 121 |
+
},
|
| 122 |
+
"repo_id": "ElnaggarLab/ankh2-ext2",
|
| 123 |
+
"revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8",
|
| 124 |
+
"unresolved_files": []
|
| 125 |
+
},
|
| 126 |
+
"oracle_assets": [],
|
| 127 |
+
"redistributable": true,
|
| 128 |
+
"release_tool_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 129 |
+
"release_tool_sha256": "1459b5d7d13d9b07bd97b3eee764f2ce73623e15e32d07ddf6825c2a9509afb9",
|
| 130 |
+
"runtime_assets": [],
|
| 131 |
+
"runtime_bundle_sha256": "17b8f83a33e63d941e3edfb8db2d8381286046b572f94194e576ca394d997597",
|
| 132 |
+
"runtime_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 133 |
+
"schema_version": 4,
|
| 134 |
+
"source_tree_sha256": "5eb598fd991b5447e3bb6a18c92bd2300be1d94a1e169504725bc56127c1d6bc",
|
| 135 |
+
"state_transform": "ankh_t5_to_fastplms_v1",
|
| 136 |
+
"tokenizer_auto_map": null,
|
| 137 |
+
"tokenizer_checkpoint": {
|
| 138 |
+
"files": {
|
| 139 |
+
"special_tokens_map.json": "git-sha1:55b145827029ae9672e50d4bb368540daacce791",
|
| 140 |
+
"tokenizer.json": "git-sha1:212c5ef08819fa2463c6289ba4ef7db30e715c0a",
|
| 141 |
+
"tokenizer_config.json": "git-sha1:854e5db75dae8b1e9dd39c5bae80dae5508b3e25"
|
| 142 |
+
},
|
| 143 |
+
"repo_id": "ElnaggarLab/ankh2-ext2",
|
| 144 |
+
"revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8",
|
| 145 |
+
"unresolved_files": []
|
| 146 |
+
},
|
| 147 |
+
"tokenizer_class": null,
|
| 148 |
+
"upstreams": [
|
| 149 |
+
{
|
| 150 |
+
"canonical_license_files": {
|
| 151 |
+
"LICENSE.md": "sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088"
|
| 152 |
+
},
|
| 153 |
+
"distribution_files": {
|
| 154 |
+
"LICENSE.md": "sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088"
|
| 155 |
+
},
|
| 156 |
+
"id": "ankh",
|
| 157 |
+
"license": "CC-BY-NC-SA-4.0",
|
| 158 |
+
"path": "vendor/upstream/ankh",
|
| 159 |
+
"revision": "02b4e25ce5389b9e771c9df6e546c62af1216f8e",
|
| 160 |
+
"url": "https://github.com/agemagician/Ankh.git"
|
| 161 |
+
}
|
| 162 |
+
],
|
| 163 |
+
"weights_license_status": "resolved",
|
| 164 |
+
"weights_revision": "aa9b9fa72288c47d9f618ce80c011e24b54e17a8"
|
| 165 |
+
}
|
runtime-attestation.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"files": {
|
| 3 |
+
"LICENSES/FastPLMs-Apache-2.0.txt": "sha256:2d2b50c7b1414bff1189a1db1f0cfb92e3e064b50f4c2b1019827b683e1b629a",
|
| 4 |
+
"LICENSES/ankh/LICENSE.md": "sha256:cd041d7f9f52936e8824ac3f754e9c67410763205fc8a7020ba74fc8b6edc088",
|
| 5 |
+
"README.md": "sha256:d34607e87e0df11a9d8cea1e8dd541d1fe79761f90cfc2d95c9cb5135e0ccbbc",
|
| 6 |
+
"THIRD_PARTY_NOTICES.md": "sha256:25704b3c76404696cae52e7fca13088d329f70f412687340351259e86cd62baa",
|
| 7 |
+
"config.json": "sha256:fe9df500b8e73df29eff467f41a92d9bf1489ba7ac8c151f237f700f41b1b7a1",
|
| 8 |
+
"fastplms/__init__.py": "sha256:4fb3196022ca8ec699d59d09bdbc5f0184195552b773698ab9b061fe3cd7df12",
|
| 9 |
+
"fastplms/attention/__init__.py": "sha256:f60b9fecfb4bcb37a4e7c26dc2f752b9035f9cbad627b4a84213f3a92ec88f7d",
|
| 10 |
+
"fastplms/attention/_core.py": "sha256:8f7ec5b65bd8b6c6fa4951d50d1c0e499abf03ae00914794b51fc410201e3e33",
|
| 11 |
+
"fastplms/attention/_kernel_lock.py": "sha256:85d8521a2af5f94fad3948af3814db0c866c414ee4d43df797b9bd6f980e947b",
|
| 12 |
+
"fastplms/attention/interfaces.py": "sha256:1c6f06a8e411e0f9bf6d230522205c93ae46ea58864006fbb892aa05e5ca5749",
|
| 13 |
+
"fastplms/embeddings/__init__.py": "sha256:47ff8cdf682d44037dd9edab133e2e60675d60786bd5cf0bffd1998f31985555",
|
| 14 |
+
"fastplms/embeddings/pooling.py": "sha256:a140266ed6b1cc344c8507edc5c6c4f2dce464c3db70ba4b16c7ac2ba2fad96e",
|
| 15 |
+
"fastplms/embeddings/runner.py": "sha256:23ee4727a918d6d331f7a0f89b823d149f1a791f0c5586e3496d7b6eb2ce97e0",
|
| 16 |
+
"fastplms/embeddings/storage.py": "sha256:3fbe2bab75092e5a4cadf4d27e4752181d597469a65a55db085ceef808ed418e",
|
| 17 |
+
"fastplms/embeddings/types.py": "sha256:119718a20989d1ae5a60fabc0f5e98bdc172c5163b04db3d4554ac3956b30e52",
|
| 18 |
+
"fastplms/models.toml": "sha256:05a8399f084a5babb5f0916cee7e564c4030767f3ff0230c4f46e539209847d1",
|
| 19 |
+
"fastplms/models/__init__.py": "sha256:5e48c2cb3877aa6f42f3b5411d53b16bba2e32827bbde634f47f174c5cb36f86",
|
| 20 |
+
"fastplms/models/ankh/__init__.py": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 21 |
+
"fastplms/models/ankh/modeling_ankh.py": "sha256:b114c73e4aaedc567e3351b425ddddacf35661f09b3414cf59b6db0b712c82c3",
|
| 22 |
+
"fastplms/models/ttt.py": "sha256:a0df4e98b02120d423e3c7ca9b866a8d0e3748b9076042a0102a838a11aed046",
|
| 23 |
+
"fastplms/registry.py": "sha256:afca271911b651a882345b74a58366494a1d784e4a48c8683a87f5508f4ba16e",
|
| 24 |
+
"fastplms/runtime.py": "sha256:110018646d6f248cedab140a030c3065e1b062b61f6aff659c231e538614bc01",
|
| 25 |
+
"fastplms_bundle.py": "sha256:ebf70cf52fb0a07025edf06bd50d2e945d9ed09fe12e6d3ae3503001ec21c9f9",
|
| 26 |
+
"modeling_fastplms.py": "sha256:df7f6d96802eff127bc8270cde5fe00c8f5e77921c1cc893021fb9f75a3e4c77",
|
| 27 |
+
"special_tokens_map.json": "sha256:c8995d2f8037fe3a8cfdef30475365e1c314c417880b75abaf8296e3c05d42d6",
|
| 28 |
+
"tokenizer.json": "sha256:b4533f607d9fd665f2d9d94b0cf71870a6fc2fc2ae7cbd516d0e43a9efb406fd",
|
| 29 |
+
"tokenizer_config.json": "sha256:dba1f9315ded007fc2e5bcb2ed4bfb6fff81c9becdc97b73a5713ba5ddc01afc"
|
| 30 |
+
},
|
| 31 |
+
"model_id": "ankh2_large",
|
| 32 |
+
"redistributable": true,
|
| 33 |
+
"release_tool_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 34 |
+
"release_tool_sha256": "1459b5d7d13d9b07bd97b3eee764f2ce73623e15e32d07ddf6825c2a9509afb9",
|
| 35 |
+
"runtime_bundle_sha256": "17b8f83a33e63d941e3edfb8db2d8381286046b572f94194e576ca394d997597",
|
| 36 |
+
"runtime_revision": "1b9ce023f1e06571cf3e6324be0610ffa53e0a4a",
|
| 37 |
+
"schema_version": 2,
|
| 38 |
+
"scope": "runtime-only",
|
| 39 |
+
"source_tree_sha256": "5eb598fd991b5447e3bb6a18c92bd2300be1d94a1e169504725bc56127c1d6bc",
|
| 40 |
+
"weights": {
|
| 41 |
+
"repo_id": "Synthyra/ANKH2_large",
|
| 42 |
+
"revision": "392de5ed52bbfd73b45f545e378aaebcff096d0e"
|
| 43 |
+
},
|
| 44 |
+
"weights_license_status": "resolved"
|
| 45 |
+
}
|
special_tokens_map.json
CHANGED
|
@@ -117,32 +117,8 @@
|
|
| 117 |
"<extra_id_114>",
|
| 118 |
"<extra_id_115>"
|
| 119 |
],
|
| 120 |
-
"eos_token":
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
"rstrip": false,
|
| 125 |
-
"single_word": false
|
| 126 |
-
},
|
| 127 |
-
"mask_token": {
|
| 128 |
-
"content": "<extra_id_0>",
|
| 129 |
-
"lstrip": false,
|
| 130 |
-
"normalized": false,
|
| 131 |
-
"rstrip": false,
|
| 132 |
-
"single_word": false
|
| 133 |
-
},
|
| 134 |
-
"pad_token": {
|
| 135 |
-
"content": "<pad>",
|
| 136 |
-
"lstrip": false,
|
| 137 |
-
"normalized": false,
|
| 138 |
-
"rstrip": false,
|
| 139 |
-
"single_word": false
|
| 140 |
-
},
|
| 141 |
-
"unk_token": {
|
| 142 |
-
"content": "<unk>",
|
| 143 |
-
"lstrip": false,
|
| 144 |
-
"normalized": false,
|
| 145 |
-
"rstrip": false,
|
| 146 |
-
"single_word": false
|
| 147 |
-
}
|
| 148 |
}
|
|
|
|
| 117 |
"<extra_id_114>",
|
| 118 |
"<extra_id_115>"
|
| 119 |
],
|
| 120 |
+
"eos_token": "</s>",
|
| 121 |
+
"mask_token": "<extra_id_0>",
|
| 122 |
+
"pad_token": "<pad>",
|
| 123 |
+
"unk_token": "<unk>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
}
|
tokenizer.json
CHANGED
|
@@ -1134,8 +1134,7 @@
|
|
| 1134 |
"decoder": {
|
| 1135 |
"type": "Metaspace",
|
| 1136 |
"replacement": "▁",
|
| 1137 |
-
"
|
| 1138 |
-
"split": true
|
| 1139 |
},
|
| 1140 |
"model": {
|
| 1141 |
"type": "Unigram",
|
|
@@ -1717,7 +1716,6 @@
|
|
| 1717 |
"<extra_id_0>",
|
| 1718 |
0.0
|
| 1719 |
]
|
| 1720 |
-
]
|
| 1721 |
-
"byte_fallback": false
|
| 1722 |
}
|
| 1723 |
}
|
|
|
|
| 1134 |
"decoder": {
|
| 1135 |
"type": "Metaspace",
|
| 1136 |
"replacement": "▁",
|
| 1137 |
+
"add_prefix_space": true
|
|
|
|
| 1138 |
},
|
| 1139 |
"model": {
|
| 1140 |
"type": "Unigram",
|
|
|
|
| 1716 |
"<extra_id_0>",
|
| 1717 |
0.0
|
| 1718 |
]
|
| 1719 |
+
]
|
|
|
|
| 1720 |
}
|
| 1721 |
}
|
tokenizer_config.json
CHANGED
|
@@ -1,959 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"add_prefix_space": null,
|
| 3 |
-
"added_tokens_decoder": {
|
| 4 |
-
"0": {
|
| 5 |
-
"content": "<pad>",
|
| 6 |
-
"lstrip": false,
|
| 7 |
-
"normalized": false,
|
| 8 |
-
"rstrip": false,
|
| 9 |
-
"single_word": false,
|
| 10 |
-
"special": true
|
| 11 |
-
},
|
| 12 |
-
"1": {
|
| 13 |
-
"content": "</s>",
|
| 14 |
-
"lstrip": false,
|
| 15 |
-
"normalized": false,
|
| 16 |
-
"rstrip": false,
|
| 17 |
-
"single_word": false,
|
| 18 |
-
"special": true
|
| 19 |
-
},
|
| 20 |
-
"2": {
|
| 21 |
-
"content": "<unk>",
|
| 22 |
-
"lstrip": false,
|
| 23 |
-
"normalized": false,
|
| 24 |
-
"rstrip": false,
|
| 25 |
-
"single_word": false,
|
| 26 |
-
"special": true
|
| 27 |
-
},
|
| 28 |
-
"28": {
|
| 29 |
-
"content": "<extra_id_115>",
|
| 30 |
-
"lstrip": false,
|
| 31 |
-
"normalized": false,
|
| 32 |
-
"rstrip": false,
|
| 33 |
-
"single_word": false,
|
| 34 |
-
"special": true
|
| 35 |
-
},
|
| 36 |
-
"29": {
|
| 37 |
-
"content": "<extra_id_114>",
|
| 38 |
-
"lstrip": false,
|
| 39 |
-
"normalized": false,
|
| 40 |
-
"rstrip": false,
|
| 41 |
-
"single_word": false,
|
| 42 |
-
"special": true
|
| 43 |
-
},
|
| 44 |
-
"30": {
|
| 45 |
-
"content": "<extra_id_113>",
|
| 46 |
-
"lstrip": false,
|
| 47 |
-
"normalized": false,
|
| 48 |
-
"rstrip": false,
|
| 49 |
-
"single_word": false,
|
| 50 |
-
"special": true
|
| 51 |
-
},
|
| 52 |
-
"31": {
|
| 53 |
-
"content": "<extra_id_112>",
|
| 54 |
-
"lstrip": false,
|
| 55 |
-
"normalized": false,
|
| 56 |
-
"rstrip": false,
|
| 57 |
-
"single_word": false,
|
| 58 |
-
"special": true
|
| 59 |
-
},
|
| 60 |
-
"32": {
|
| 61 |
-
"content": "<extra_id_111>",
|
| 62 |
-
"lstrip": false,
|
| 63 |
-
"normalized": false,
|
| 64 |
-
"rstrip": false,
|
| 65 |
-
"single_word": false,
|
| 66 |
-
"special": true
|
| 67 |
-
},
|
| 68 |
-
"33": {
|
| 69 |
-
"content": "<extra_id_110>",
|
| 70 |
-
"lstrip": false,
|
| 71 |
-
"normalized": false,
|
| 72 |
-
"rstrip": false,
|
| 73 |
-
"single_word": false,
|
| 74 |
-
"special": true
|
| 75 |
-
},
|
| 76 |
-
"34": {
|
| 77 |
-
"content": "<extra_id_109>",
|
| 78 |
-
"lstrip": false,
|
| 79 |
-
"normalized": false,
|
| 80 |
-
"rstrip": false,
|
| 81 |
-
"single_word": false,
|
| 82 |
-
"special": true
|
| 83 |
-
},
|
| 84 |
-
"35": {
|
| 85 |
-
"content": "<extra_id_108>",
|
| 86 |
-
"lstrip": false,
|
| 87 |
-
"normalized": false,
|
| 88 |
-
"rstrip": false,
|
| 89 |
-
"single_word": false,
|
| 90 |
-
"special": true
|
| 91 |
-
},
|
| 92 |
-
"36": {
|
| 93 |
-
"content": "<extra_id_107>",
|
| 94 |
-
"lstrip": false,
|
| 95 |
-
"normalized": false,
|
| 96 |
-
"rstrip": false,
|
| 97 |
-
"single_word": false,
|
| 98 |
-
"special": true
|
| 99 |
-
},
|
| 100 |
-
"37": {
|
| 101 |
-
"content": "<extra_id_106>",
|
| 102 |
-
"lstrip": false,
|
| 103 |
-
"normalized": false,
|
| 104 |
-
"rstrip": false,
|
| 105 |
-
"single_word": false,
|
| 106 |
-
"special": true
|
| 107 |
-
},
|
| 108 |
-
"38": {
|
| 109 |
-
"content": "<extra_id_105>",
|
| 110 |
-
"lstrip": false,
|
| 111 |
-
"normalized": false,
|
| 112 |
-
"rstrip": false,
|
| 113 |
-
"single_word": false,
|
| 114 |
-
"special": true
|
| 115 |
-
},
|
| 116 |
-
"39": {
|
| 117 |
-
"content": "<extra_id_104>",
|
| 118 |
-
"lstrip": false,
|
| 119 |
-
"normalized": false,
|
| 120 |
-
"rstrip": false,
|
| 121 |
-
"single_word": false,
|
| 122 |
-
"special": true
|
| 123 |
-
},
|
| 124 |
-
"40": {
|
| 125 |
-
"content": "<extra_id_103>",
|
| 126 |
-
"lstrip": false,
|
| 127 |
-
"normalized": false,
|
| 128 |
-
"rstrip": false,
|
| 129 |
-
"single_word": false,
|
| 130 |
-
"special": true
|
| 131 |
-
},
|
| 132 |
-
"41": {
|
| 133 |
-
"content": "<extra_id_102>",
|
| 134 |
-
"lstrip": false,
|
| 135 |
-
"normalized": false,
|
| 136 |
-
"rstrip": false,
|
| 137 |
-
"single_word": false,
|
| 138 |
-
"special": true
|
| 139 |
-
},
|
| 140 |
-
"42": {
|
| 141 |
-
"content": "<extra_id_101>",
|
| 142 |
-
"lstrip": false,
|
| 143 |
-
"normalized": false,
|
| 144 |
-
"rstrip": false,
|
| 145 |
-
"single_word": false,
|
| 146 |
-
"special": true
|
| 147 |
-
},
|
| 148 |
-
"43": {
|
| 149 |
-
"content": "<extra_id_100>",
|
| 150 |
-
"lstrip": false,
|
| 151 |
-
"normalized": false,
|
| 152 |
-
"rstrip": false,
|
| 153 |
-
"single_word": false,
|
| 154 |
-
"special": true
|
| 155 |
-
},
|
| 156 |
-
"44": {
|
| 157 |
-
"content": "<extra_id_99>",
|
| 158 |
-
"lstrip": false,
|
| 159 |
-
"normalized": false,
|
| 160 |
-
"rstrip": false,
|
| 161 |
-
"single_word": false,
|
| 162 |
-
"special": true
|
| 163 |
-
},
|
| 164 |
-
"45": {
|
| 165 |
-
"content": "<extra_id_98>",
|
| 166 |
-
"lstrip": false,
|
| 167 |
-
"normalized": false,
|
| 168 |
-
"rstrip": false,
|
| 169 |
-
"single_word": false,
|
| 170 |
-
"special": true
|
| 171 |
-
},
|
| 172 |
-
"46": {
|
| 173 |
-
"content": "<extra_id_97>",
|
| 174 |
-
"lstrip": false,
|
| 175 |
-
"normalized": false,
|
| 176 |
-
"rstrip": false,
|
| 177 |
-
"single_word": false,
|
| 178 |
-
"special": true
|
| 179 |
-
},
|
| 180 |
-
"47": {
|
| 181 |
-
"content": "<extra_id_96>",
|
| 182 |
-
"lstrip": false,
|
| 183 |
-
"normalized": false,
|
| 184 |
-
"rstrip": false,
|
| 185 |
-
"single_word": false,
|
| 186 |
-
"special": true
|
| 187 |
-
},
|
| 188 |
-
"48": {
|
| 189 |
-
"content": "<extra_id_95>",
|
| 190 |
-
"lstrip": false,
|
| 191 |
-
"normalized": false,
|
| 192 |
-
"rstrip": false,
|
| 193 |
-
"single_word": false,
|
| 194 |
-
"special": true
|
| 195 |
-
},
|
| 196 |
-
"49": {
|
| 197 |
-
"content": "<extra_id_94>",
|
| 198 |
-
"lstrip": false,
|
| 199 |
-
"normalized": false,
|
| 200 |
-
"rstrip": false,
|
| 201 |
-
"single_word": false,
|
| 202 |
-
"special": true
|
| 203 |
-
},
|
| 204 |
-
"50": {
|
| 205 |
-
"content": "<extra_id_93>",
|
| 206 |
-
"lstrip": false,
|
| 207 |
-
"normalized": false,
|
| 208 |
-
"rstrip": false,
|
| 209 |
-
"single_word": false,
|
| 210 |
-
"special": true
|
| 211 |
-
},
|
| 212 |
-
"51": {
|
| 213 |
-
"content": "<extra_id_92>",
|
| 214 |
-
"lstrip": false,
|
| 215 |
-
"normalized": false,
|
| 216 |
-
"rstrip": false,
|
| 217 |
-
"single_word": false,
|
| 218 |
-
"special": true
|
| 219 |
-
},
|
| 220 |
-
"52": {
|
| 221 |
-
"content": "<extra_id_91>",
|
| 222 |
-
"lstrip": false,
|
| 223 |
-
"normalized": false,
|
| 224 |
-
"rstrip": false,
|
| 225 |
-
"single_word": false,
|
| 226 |
-
"special": true
|
| 227 |
-
},
|
| 228 |
-
"53": {
|
| 229 |
-
"content": "<extra_id_90>",
|
| 230 |
-
"lstrip": false,
|
| 231 |
-
"normalized": false,
|
| 232 |
-
"rstrip": false,
|
| 233 |
-
"single_word": false,
|
| 234 |
-
"special": true
|
| 235 |
-
},
|
| 236 |
-
"54": {
|
| 237 |
-
"content": "<extra_id_89>",
|
| 238 |
-
"lstrip": false,
|
| 239 |
-
"normalized": false,
|
| 240 |
-
"rstrip": false,
|
| 241 |
-
"single_word": false,
|
| 242 |
-
"special": true
|
| 243 |
-
},
|
| 244 |
-
"55": {
|
| 245 |
-
"content": "<extra_id_88>",
|
| 246 |
-
"lstrip": false,
|
| 247 |
-
"normalized": false,
|
| 248 |
-
"rstrip": false,
|
| 249 |
-
"single_word": false,
|
| 250 |
-
"special": true
|
| 251 |
-
},
|
| 252 |
-
"56": {
|
| 253 |
-
"content": "<extra_id_87>",
|
| 254 |
-
"lstrip": false,
|
| 255 |
-
"normalized": false,
|
| 256 |
-
"rstrip": false,
|
| 257 |
-
"single_word": false,
|
| 258 |
-
"special": true
|
| 259 |
-
},
|
| 260 |
-
"57": {
|
| 261 |
-
"content": "<extra_id_86>",
|
| 262 |
-
"lstrip": false,
|
| 263 |
-
"normalized": false,
|
| 264 |
-
"rstrip": false,
|
| 265 |
-
"single_word": false,
|
| 266 |
-
"special": true
|
| 267 |
-
},
|
| 268 |
-
"58": {
|
| 269 |
-
"content": "<extra_id_85>",
|
| 270 |
-
"lstrip": false,
|
| 271 |
-
"normalized": false,
|
| 272 |
-
"rstrip": false,
|
| 273 |
-
"single_word": false,
|
| 274 |
-
"special": true
|
| 275 |
-
},
|
| 276 |
-
"59": {
|
| 277 |
-
"content": "<extra_id_84>",
|
| 278 |
-
"lstrip": false,
|
| 279 |
-
"normalized": false,
|
| 280 |
-
"rstrip": false,
|
| 281 |
-
"single_word": false,
|
| 282 |
-
"special": true
|
| 283 |
-
},
|
| 284 |
-
"60": {
|
| 285 |
-
"content": "<extra_id_83>",
|
| 286 |
-
"lstrip": false,
|
| 287 |
-
"normalized": false,
|
| 288 |
-
"rstrip": false,
|
| 289 |
-
"single_word": false,
|
| 290 |
-
"special": true
|
| 291 |
-
},
|
| 292 |
-
"61": {
|
| 293 |
-
"content": "<extra_id_82>",
|
| 294 |
-
"lstrip": false,
|
| 295 |
-
"normalized": false,
|
| 296 |
-
"rstrip": false,
|
| 297 |
-
"single_word": false,
|
| 298 |
-
"special": true
|
| 299 |
-
},
|
| 300 |
-
"62": {
|
| 301 |
-
"content": "<extra_id_81>",
|
| 302 |
-
"lstrip": false,
|
| 303 |
-
"normalized": false,
|
| 304 |
-
"rstrip": false,
|
| 305 |
-
"single_word": false,
|
| 306 |
-
"special": true
|
| 307 |
-
},
|
| 308 |
-
"63": {
|
| 309 |
-
"content": "<extra_id_80>",
|
| 310 |
-
"lstrip": false,
|
| 311 |
-
"normalized": false,
|
| 312 |
-
"rstrip": false,
|
| 313 |
-
"single_word": false,
|
| 314 |
-
"special": true
|
| 315 |
-
},
|
| 316 |
-
"64": {
|
| 317 |
-
"content": "<extra_id_79>",
|
| 318 |
-
"lstrip": false,
|
| 319 |
-
"normalized": false,
|
| 320 |
-
"rstrip": false,
|
| 321 |
-
"single_word": false,
|
| 322 |
-
"special": true
|
| 323 |
-
},
|
| 324 |
-
"65": {
|
| 325 |
-
"content": "<extra_id_78>",
|
| 326 |
-
"lstrip": false,
|
| 327 |
-
"normalized": false,
|
| 328 |
-
"rstrip": false,
|
| 329 |
-
"single_word": false,
|
| 330 |
-
"special": true
|
| 331 |
-
},
|
| 332 |
-
"66": {
|
| 333 |
-
"content": "<extra_id_77>",
|
| 334 |
-
"lstrip": false,
|
| 335 |
-
"normalized": false,
|
| 336 |
-
"rstrip": false,
|
| 337 |
-
"single_word": false,
|
| 338 |
-
"special": true
|
| 339 |
-
},
|
| 340 |
-
"67": {
|
| 341 |
-
"content": "<extra_id_76>",
|
| 342 |
-
"lstrip": false,
|
| 343 |
-
"normalized": false,
|
| 344 |
-
"rstrip": false,
|
| 345 |
-
"single_word": false,
|
| 346 |
-
"special": true
|
| 347 |
-
},
|
| 348 |
-
"68": {
|
| 349 |
-
"content": "<extra_id_75>",
|
| 350 |
-
"lstrip": false,
|
| 351 |
-
"normalized": false,
|
| 352 |
-
"rstrip": false,
|
| 353 |
-
"single_word": false,
|
| 354 |
-
"special": true
|
| 355 |
-
},
|
| 356 |
-
"69": {
|
| 357 |
-
"content": "<extra_id_74>",
|
| 358 |
-
"lstrip": false,
|
| 359 |
-
"normalized": false,
|
| 360 |
-
"rstrip": false,
|
| 361 |
-
"single_word": false,
|
| 362 |
-
"special": true
|
| 363 |
-
},
|
| 364 |
-
"70": {
|
| 365 |
-
"content": "<extra_id_73>",
|
| 366 |
-
"lstrip": false,
|
| 367 |
-
"normalized": false,
|
| 368 |
-
"rstrip": false,
|
| 369 |
-
"single_word": false,
|
| 370 |
-
"special": true
|
| 371 |
-
},
|
| 372 |
-
"71": {
|
| 373 |
-
"content": "<extra_id_72>",
|
| 374 |
-
"lstrip": false,
|
| 375 |
-
"normalized": false,
|
| 376 |
-
"rstrip": false,
|
| 377 |
-
"single_word": false,
|
| 378 |
-
"special": true
|
| 379 |
-
},
|
| 380 |
-
"72": {
|
| 381 |
-
"content": "<extra_id_71>",
|
| 382 |
-
"lstrip": false,
|
| 383 |
-
"normalized": false,
|
| 384 |
-
"rstrip": false,
|
| 385 |
-
"single_word": false,
|
| 386 |
-
"special": true
|
| 387 |
-
},
|
| 388 |
-
"73": {
|
| 389 |
-
"content": "<extra_id_70>",
|
| 390 |
-
"lstrip": false,
|
| 391 |
-
"normalized": false,
|
| 392 |
-
"rstrip": false,
|
| 393 |
-
"single_word": false,
|
| 394 |
-
"special": true
|
| 395 |
-
},
|
| 396 |
-
"74": {
|
| 397 |
-
"content": "<extra_id_69>",
|
| 398 |
-
"lstrip": false,
|
| 399 |
-
"normalized": false,
|
| 400 |
-
"rstrip": false,
|
| 401 |
-
"single_word": false,
|
| 402 |
-
"special": true
|
| 403 |
-
},
|
| 404 |
-
"75": {
|
| 405 |
-
"content": "<extra_id_68>",
|
| 406 |
-
"lstrip": false,
|
| 407 |
-
"normalized": false,
|
| 408 |
-
"rstrip": false,
|
| 409 |
-
"single_word": false,
|
| 410 |
-
"special": true
|
| 411 |
-
},
|
| 412 |
-
"76": {
|
| 413 |
-
"content": "<extra_id_67>",
|
| 414 |
-
"lstrip": false,
|
| 415 |
-
"normalized": false,
|
| 416 |
-
"rstrip": false,
|
| 417 |
-
"single_word": false,
|
| 418 |
-
"special": true
|
| 419 |
-
},
|
| 420 |
-
"77": {
|
| 421 |
-
"content": "<extra_id_66>",
|
| 422 |
-
"lstrip": false,
|
| 423 |
-
"normalized": false,
|
| 424 |
-
"rstrip": false,
|
| 425 |
-
"single_word": false,
|
| 426 |
-
"special": true
|
| 427 |
-
},
|
| 428 |
-
"78": {
|
| 429 |
-
"content": "<extra_id_65>",
|
| 430 |
-
"lstrip": false,
|
| 431 |
-
"normalized": false,
|
| 432 |
-
"rstrip": false,
|
| 433 |
-
"single_word": false,
|
| 434 |
-
"special": true
|
| 435 |
-
},
|
| 436 |
-
"79": {
|
| 437 |
-
"content": "<extra_id_64>",
|
| 438 |
-
"lstrip": false,
|
| 439 |
-
"normalized": false,
|
| 440 |
-
"rstrip": false,
|
| 441 |
-
"single_word": false,
|
| 442 |
-
"special": true
|
| 443 |
-
},
|
| 444 |
-
"80": {
|
| 445 |
-
"content": "<extra_id_63>",
|
| 446 |
-
"lstrip": false,
|
| 447 |
-
"normalized": false,
|
| 448 |
-
"rstrip": false,
|
| 449 |
-
"single_word": false,
|
| 450 |
-
"special": true
|
| 451 |
-
},
|
| 452 |
-
"81": {
|
| 453 |
-
"content": "<extra_id_62>",
|
| 454 |
-
"lstrip": false,
|
| 455 |
-
"normalized": false,
|
| 456 |
-
"rstrip": false,
|
| 457 |
-
"single_word": false,
|
| 458 |
-
"special": true
|
| 459 |
-
},
|
| 460 |
-
"82": {
|
| 461 |
-
"content": "<extra_id_61>",
|
| 462 |
-
"lstrip": false,
|
| 463 |
-
"normalized": false,
|
| 464 |
-
"rstrip": false,
|
| 465 |
-
"single_word": false,
|
| 466 |
-
"special": true
|
| 467 |
-
},
|
| 468 |
-
"83": {
|
| 469 |
-
"content": "<extra_id_60>",
|
| 470 |
-
"lstrip": false,
|
| 471 |
-
"normalized": false,
|
| 472 |
-
"rstrip": false,
|
| 473 |
-
"single_word": false,
|
| 474 |
-
"special": true
|
| 475 |
-
},
|
| 476 |
-
"84": {
|
| 477 |
-
"content": "<extra_id_59>",
|
| 478 |
-
"lstrip": false,
|
| 479 |
-
"normalized": false,
|
| 480 |
-
"rstrip": false,
|
| 481 |
-
"single_word": false,
|
| 482 |
-
"special": true
|
| 483 |
-
},
|
| 484 |
-
"85": {
|
| 485 |
-
"content": "<extra_id_58>",
|
| 486 |
-
"lstrip": false,
|
| 487 |
-
"normalized": false,
|
| 488 |
-
"rstrip": false,
|
| 489 |
-
"single_word": false,
|
| 490 |
-
"special": true
|
| 491 |
-
},
|
| 492 |
-
"86": {
|
| 493 |
-
"content": "<extra_id_57>",
|
| 494 |
-
"lstrip": false,
|
| 495 |
-
"normalized": false,
|
| 496 |
-
"rstrip": false,
|
| 497 |
-
"single_word": false,
|
| 498 |
-
"special": true
|
| 499 |
-
},
|
| 500 |
-
"87": {
|
| 501 |
-
"content": "<extra_id_56>",
|
| 502 |
-
"lstrip": false,
|
| 503 |
-
"normalized": false,
|
| 504 |
-
"rstrip": false,
|
| 505 |
-
"single_word": false,
|
| 506 |
-
"special": true
|
| 507 |
-
},
|
| 508 |
-
"88": {
|
| 509 |
-
"content": "<extra_id_55>",
|
| 510 |
-
"lstrip": false,
|
| 511 |
-
"normalized": false,
|
| 512 |
-
"rstrip": false,
|
| 513 |
-
"single_word": false,
|
| 514 |
-
"special": true
|
| 515 |
-
},
|
| 516 |
-
"89": {
|
| 517 |
-
"content": "<extra_id_54>",
|
| 518 |
-
"lstrip": false,
|
| 519 |
-
"normalized": false,
|
| 520 |
-
"rstrip": false,
|
| 521 |
-
"single_word": false,
|
| 522 |
-
"special": true
|
| 523 |
-
},
|
| 524 |
-
"90": {
|
| 525 |
-
"content": "<extra_id_53>",
|
| 526 |
-
"lstrip": false,
|
| 527 |
-
"normalized": false,
|
| 528 |
-
"rstrip": false,
|
| 529 |
-
"single_word": false,
|
| 530 |
-
"special": true
|
| 531 |
-
},
|
| 532 |
-
"91": {
|
| 533 |
-
"content": "<extra_id_52>",
|
| 534 |
-
"lstrip": false,
|
| 535 |
-
"normalized": false,
|
| 536 |
-
"rstrip": false,
|
| 537 |
-
"single_word": false,
|
| 538 |
-
"special": true
|
| 539 |
-
},
|
| 540 |
-
"92": {
|
| 541 |
-
"content": "<extra_id_51>",
|
| 542 |
-
"lstrip": false,
|
| 543 |
-
"normalized": false,
|
| 544 |
-
"rstrip": false,
|
| 545 |
-
"single_word": false,
|
| 546 |
-
"special": true
|
| 547 |
-
},
|
| 548 |
-
"93": {
|
| 549 |
-
"content": "<extra_id_50>",
|
| 550 |
-
"lstrip": false,
|
| 551 |
-
"normalized": false,
|
| 552 |
-
"rstrip": false,
|
| 553 |
-
"single_word": false,
|
| 554 |
-
"special": true
|
| 555 |
-
},
|
| 556 |
-
"94": {
|
| 557 |
-
"content": "<extra_id_49>",
|
| 558 |
-
"lstrip": false,
|
| 559 |
-
"normalized": false,
|
| 560 |
-
"rstrip": false,
|
| 561 |
-
"single_word": false,
|
| 562 |
-
"special": true
|
| 563 |
-
},
|
| 564 |
-
"95": {
|
| 565 |
-
"content": "<extra_id_48>",
|
| 566 |
-
"lstrip": false,
|
| 567 |
-
"normalized": false,
|
| 568 |
-
"rstrip": false,
|
| 569 |
-
"single_word": false,
|
| 570 |
-
"special": true
|
| 571 |
-
},
|
| 572 |
-
"96": {
|
| 573 |
-
"content": "<extra_id_47>",
|
| 574 |
-
"lstrip": false,
|
| 575 |
-
"normalized": false,
|
| 576 |
-
"rstrip": false,
|
| 577 |
-
"single_word": false,
|
| 578 |
-
"special": true
|
| 579 |
-
},
|
| 580 |
-
"97": {
|
| 581 |
-
"content": "<extra_id_46>",
|
| 582 |
-
"lstrip": false,
|
| 583 |
-
"normalized": false,
|
| 584 |
-
"rstrip": false,
|
| 585 |
-
"single_word": false,
|
| 586 |
-
"special": true
|
| 587 |
-
},
|
| 588 |
-
"98": {
|
| 589 |
-
"content": "<extra_id_45>",
|
| 590 |
-
"lstrip": false,
|
| 591 |
-
"normalized": false,
|
| 592 |
-
"rstrip": false,
|
| 593 |
-
"single_word": false,
|
| 594 |
-
"special": true
|
| 595 |
-
},
|
| 596 |
-
"99": {
|
| 597 |
-
"content": "<extra_id_44>",
|
| 598 |
-
"lstrip": false,
|
| 599 |
-
"normalized": false,
|
| 600 |
-
"rstrip": false,
|
| 601 |
-
"single_word": false,
|
| 602 |
-
"special": true
|
| 603 |
-
},
|
| 604 |
-
"100": {
|
| 605 |
-
"content": "<extra_id_43>",
|
| 606 |
-
"lstrip": false,
|
| 607 |
-
"normalized": false,
|
| 608 |
-
"rstrip": false,
|
| 609 |
-
"single_word": false,
|
| 610 |
-
"special": true
|
| 611 |
-
},
|
| 612 |
-
"101": {
|
| 613 |
-
"content": "<extra_id_42>",
|
| 614 |
-
"lstrip": false,
|
| 615 |
-
"normalized": false,
|
| 616 |
-
"rstrip": false,
|
| 617 |
-
"single_word": false,
|
| 618 |
-
"special": true
|
| 619 |
-
},
|
| 620 |
-
"102": {
|
| 621 |
-
"content": "<extra_id_41>",
|
| 622 |
-
"lstrip": false,
|
| 623 |
-
"normalized": false,
|
| 624 |
-
"rstrip": false,
|
| 625 |
-
"single_word": false,
|
| 626 |
-
"special": true
|
| 627 |
-
},
|
| 628 |
-
"103": {
|
| 629 |
-
"content": "<extra_id_40>",
|
| 630 |
-
"lstrip": false,
|
| 631 |
-
"normalized": false,
|
| 632 |
-
"rstrip": false,
|
| 633 |
-
"single_word": false,
|
| 634 |
-
"special": true
|
| 635 |
-
},
|
| 636 |
-
"104": {
|
| 637 |
-
"content": "<extra_id_39>",
|
| 638 |
-
"lstrip": false,
|
| 639 |
-
"normalized": false,
|
| 640 |
-
"rstrip": false,
|
| 641 |
-
"single_word": false,
|
| 642 |
-
"special": true
|
| 643 |
-
},
|
| 644 |
-
"105": {
|
| 645 |
-
"content": "<extra_id_38>",
|
| 646 |
-
"lstrip": false,
|
| 647 |
-
"normalized": false,
|
| 648 |
-
"rstrip": false,
|
| 649 |
-
"single_word": false,
|
| 650 |
-
"special": true
|
| 651 |
-
},
|
| 652 |
-
"106": {
|
| 653 |
-
"content": "<extra_id_37>",
|
| 654 |
-
"lstrip": false,
|
| 655 |
-
"normalized": false,
|
| 656 |
-
"rstrip": false,
|
| 657 |
-
"single_word": false,
|
| 658 |
-
"special": true
|
| 659 |
-
},
|
| 660 |
-
"107": {
|
| 661 |
-
"content": "<extra_id_36>",
|
| 662 |
-
"lstrip": false,
|
| 663 |
-
"normalized": false,
|
| 664 |
-
"rstrip": false,
|
| 665 |
-
"single_word": false,
|
| 666 |
-
"special": true
|
| 667 |
-
},
|
| 668 |
-
"108": {
|
| 669 |
-
"content": "<extra_id_35>",
|
| 670 |
-
"lstrip": false,
|
| 671 |
-
"normalized": false,
|
| 672 |
-
"rstrip": false,
|
| 673 |
-
"single_word": false,
|
| 674 |
-
"special": true
|
| 675 |
-
},
|
| 676 |
-
"109": {
|
| 677 |
-
"content": "<extra_id_34>",
|
| 678 |
-
"lstrip": false,
|
| 679 |
-
"normalized": false,
|
| 680 |
-
"rstrip": false,
|
| 681 |
-
"single_word": false,
|
| 682 |
-
"special": true
|
| 683 |
-
},
|
| 684 |
-
"110": {
|
| 685 |
-
"content": "<extra_id_33>",
|
| 686 |
-
"lstrip": false,
|
| 687 |
-
"normalized": false,
|
| 688 |
-
"rstrip": false,
|
| 689 |
-
"single_word": false,
|
| 690 |
-
"special": true
|
| 691 |
-
},
|
| 692 |
-
"111": {
|
| 693 |
-
"content": "<extra_id_32>",
|
| 694 |
-
"lstrip": false,
|
| 695 |
-
"normalized": false,
|
| 696 |
-
"rstrip": false,
|
| 697 |
-
"single_word": false,
|
| 698 |
-
"special": true
|
| 699 |
-
},
|
| 700 |
-
"112": {
|
| 701 |
-
"content": "<extra_id_31>",
|
| 702 |
-
"lstrip": false,
|
| 703 |
-
"normalized": false,
|
| 704 |
-
"rstrip": false,
|
| 705 |
-
"single_word": false,
|
| 706 |
-
"special": true
|
| 707 |
-
},
|
| 708 |
-
"113": {
|
| 709 |
-
"content": "<extra_id_30>",
|
| 710 |
-
"lstrip": false,
|
| 711 |
-
"normalized": false,
|
| 712 |
-
"rstrip": false,
|
| 713 |
-
"single_word": false,
|
| 714 |
-
"special": true
|
| 715 |
-
},
|
| 716 |
-
"114": {
|
| 717 |
-
"content": "<extra_id_29>",
|
| 718 |
-
"lstrip": false,
|
| 719 |
-
"normalized": false,
|
| 720 |
-
"rstrip": false,
|
| 721 |
-
"single_word": false,
|
| 722 |
-
"special": true
|
| 723 |
-
},
|
| 724 |
-
"115": {
|
| 725 |
-
"content": "<extra_id_28>",
|
| 726 |
-
"lstrip": false,
|
| 727 |
-
"normalized": false,
|
| 728 |
-
"rstrip": false,
|
| 729 |
-
"single_word": false,
|
| 730 |
-
"special": true
|
| 731 |
-
},
|
| 732 |
-
"116": {
|
| 733 |
-
"content": "<extra_id_27>",
|
| 734 |
-
"lstrip": false,
|
| 735 |
-
"normalized": false,
|
| 736 |
-
"rstrip": false,
|
| 737 |
-
"single_word": false,
|
| 738 |
-
"special": true
|
| 739 |
-
},
|
| 740 |
-
"117": {
|
| 741 |
-
"content": "<extra_id_26>",
|
| 742 |
-
"lstrip": false,
|
| 743 |
-
"normalized": false,
|
| 744 |
-
"rstrip": false,
|
| 745 |
-
"single_word": false,
|
| 746 |
-
"special": true
|
| 747 |
-
},
|
| 748 |
-
"118": {
|
| 749 |
-
"content": "<extra_id_25>",
|
| 750 |
-
"lstrip": false,
|
| 751 |
-
"normalized": false,
|
| 752 |
-
"rstrip": false,
|
| 753 |
-
"single_word": false,
|
| 754 |
-
"special": true
|
| 755 |
-
},
|
| 756 |
-
"119": {
|
| 757 |
-
"content": "<extra_id_24>",
|
| 758 |
-
"lstrip": false,
|
| 759 |
-
"normalized": false,
|
| 760 |
-
"rstrip": false,
|
| 761 |
-
"single_word": false,
|
| 762 |
-
"special": true
|
| 763 |
-
},
|
| 764 |
-
"120": {
|
| 765 |
-
"content": "<extra_id_23>",
|
| 766 |
-
"lstrip": false,
|
| 767 |
-
"normalized": false,
|
| 768 |
-
"rstrip": false,
|
| 769 |
-
"single_word": false,
|
| 770 |
-
"special": true
|
| 771 |
-
},
|
| 772 |
-
"121": {
|
| 773 |
-
"content": "<extra_id_22>",
|
| 774 |
-
"lstrip": false,
|
| 775 |
-
"normalized": false,
|
| 776 |
-
"rstrip": false,
|
| 777 |
-
"single_word": false,
|
| 778 |
-
"special": true
|
| 779 |
-
},
|
| 780 |
-
"122": {
|
| 781 |
-
"content": "<extra_id_21>",
|
| 782 |
-
"lstrip": false,
|
| 783 |
-
"normalized": false,
|
| 784 |
-
"rstrip": false,
|
| 785 |
-
"single_word": false,
|
| 786 |
-
"special": true
|
| 787 |
-
},
|
| 788 |
-
"123": {
|
| 789 |
-
"content": "<extra_id_20>",
|
| 790 |
-
"lstrip": false,
|
| 791 |
-
"normalized": false,
|
| 792 |
-
"rstrip": false,
|
| 793 |
-
"single_word": false,
|
| 794 |
-
"special": true
|
| 795 |
-
},
|
| 796 |
-
"124": {
|
| 797 |
-
"content": "<extra_id_19>",
|
| 798 |
-
"lstrip": false,
|
| 799 |
-
"normalized": false,
|
| 800 |
-
"rstrip": false,
|
| 801 |
-
"single_word": false,
|
| 802 |
-
"special": true
|
| 803 |
-
},
|
| 804 |
-
"125": {
|
| 805 |
-
"content": "<extra_id_18>",
|
| 806 |
-
"lstrip": false,
|
| 807 |
-
"normalized": false,
|
| 808 |
-
"rstrip": false,
|
| 809 |
-
"single_word": false,
|
| 810 |
-
"special": true
|
| 811 |
-
},
|
| 812 |
-
"126": {
|
| 813 |
-
"content": "<extra_id_17>",
|
| 814 |
-
"lstrip": false,
|
| 815 |
-
"normalized": false,
|
| 816 |
-
"rstrip": false,
|
| 817 |
-
"single_word": false,
|
| 818 |
-
"special": true
|
| 819 |
-
},
|
| 820 |
-
"127": {
|
| 821 |
-
"content": "<extra_id_16>",
|
| 822 |
-
"lstrip": false,
|
| 823 |
-
"normalized": false,
|
| 824 |
-
"rstrip": false,
|
| 825 |
-
"single_word": false,
|
| 826 |
-
"special": true
|
| 827 |
-
},
|
| 828 |
-
"128": {
|
| 829 |
-
"content": "<extra_id_15>",
|
| 830 |
-
"lstrip": false,
|
| 831 |
-
"normalized": false,
|
| 832 |
-
"rstrip": false,
|
| 833 |
-
"single_word": false,
|
| 834 |
-
"special": true
|
| 835 |
-
},
|
| 836 |
-
"129": {
|
| 837 |
-
"content": "<extra_id_14>",
|
| 838 |
-
"lstrip": false,
|
| 839 |
-
"normalized": false,
|
| 840 |
-
"rstrip": false,
|
| 841 |
-
"single_word": false,
|
| 842 |
-
"special": true
|
| 843 |
-
},
|
| 844 |
-
"130": {
|
| 845 |
-
"content": "<extra_id_13>",
|
| 846 |
-
"lstrip": false,
|
| 847 |
-
"normalized": false,
|
| 848 |
-
"rstrip": false,
|
| 849 |
-
"single_word": false,
|
| 850 |
-
"special": true
|
| 851 |
-
},
|
| 852 |
-
"131": {
|
| 853 |
-
"content": "<extra_id_12>",
|
| 854 |
-
"lstrip": false,
|
| 855 |
-
"normalized": false,
|
| 856 |
-
"rstrip": false,
|
| 857 |
-
"single_word": false,
|
| 858 |
-
"special": true
|
| 859 |
-
},
|
| 860 |
-
"132": {
|
| 861 |
-
"content": "<extra_id_11>",
|
| 862 |
-
"lstrip": false,
|
| 863 |
-
"normalized": false,
|
| 864 |
-
"rstrip": false,
|
| 865 |
-
"single_word": false,
|
| 866 |
-
"special": true
|
| 867 |
-
},
|
| 868 |
-
"133": {
|
| 869 |
-
"content": "<extra_id_10>",
|
| 870 |
-
"lstrip": false,
|
| 871 |
-
"normalized": false,
|
| 872 |
-
"rstrip": false,
|
| 873 |
-
"single_word": false,
|
| 874 |
-
"special": true
|
| 875 |
-
},
|
| 876 |
-
"134": {
|
| 877 |
-
"content": "<extra_id_9>",
|
| 878 |
-
"lstrip": false,
|
| 879 |
-
"normalized": false,
|
| 880 |
-
"rstrip": false,
|
| 881 |
-
"single_word": false,
|
| 882 |
-
"special": true
|
| 883 |
-
},
|
| 884 |
-
"135": {
|
| 885 |
-
"content": "<extra_id_8>",
|
| 886 |
-
"lstrip": false,
|
| 887 |
-
"normalized": false,
|
| 888 |
-
"rstrip": false,
|
| 889 |
-
"single_word": false,
|
| 890 |
-
"special": true
|
| 891 |
-
},
|
| 892 |
-
"136": {
|
| 893 |
-
"content": "<extra_id_7>",
|
| 894 |
-
"lstrip": false,
|
| 895 |
-
"normalized": false,
|
| 896 |
-
"rstrip": false,
|
| 897 |
-
"single_word": false,
|
| 898 |
-
"special": true
|
| 899 |
-
},
|
| 900 |
-
"137": {
|
| 901 |
-
"content": "<extra_id_6>",
|
| 902 |
-
"lstrip": false,
|
| 903 |
-
"normalized": false,
|
| 904 |
-
"rstrip": false,
|
| 905 |
-
"single_word": false,
|
| 906 |
-
"special": true
|
| 907 |
-
},
|
| 908 |
-
"138": {
|
| 909 |
-
"content": "<extra_id_5>",
|
| 910 |
-
"lstrip": false,
|
| 911 |
-
"normalized": false,
|
| 912 |
-
"rstrip": false,
|
| 913 |
-
"single_word": false,
|
| 914 |
-
"special": true
|
| 915 |
-
},
|
| 916 |
-
"139": {
|
| 917 |
-
"content": "<extra_id_4>",
|
| 918 |
-
"lstrip": false,
|
| 919 |
-
"normalized": false,
|
| 920 |
-
"rstrip": false,
|
| 921 |
-
"single_word": false,
|
| 922 |
-
"special": true
|
| 923 |
-
},
|
| 924 |
-
"140": {
|
| 925 |
-
"content": "<extra_id_3>",
|
| 926 |
-
"lstrip": false,
|
| 927 |
-
"normalized": false,
|
| 928 |
-
"rstrip": false,
|
| 929 |
-
"single_word": false,
|
| 930 |
-
"special": true
|
| 931 |
-
},
|
| 932 |
-
"141": {
|
| 933 |
-
"content": "<extra_id_2>",
|
| 934 |
-
"lstrip": false,
|
| 935 |
-
"normalized": false,
|
| 936 |
-
"rstrip": false,
|
| 937 |
-
"single_word": false,
|
| 938 |
-
"special": true
|
| 939 |
-
},
|
| 940 |
-
"142": {
|
| 941 |
-
"content": "<extra_id_1>",
|
| 942 |
-
"lstrip": false,
|
| 943 |
-
"normalized": false,
|
| 944 |
-
"rstrip": false,
|
| 945 |
-
"single_word": false,
|
| 946 |
-
"special": true
|
| 947 |
-
},
|
| 948 |
-
"143": {
|
| 949 |
-
"content": "<extra_id_0>",
|
| 950 |
-
"lstrip": false,
|
| 951 |
-
"normalized": false,
|
| 952 |
-
"rstrip": false,
|
| 953 |
-
"single_word": false,
|
| 954 |
-
"special": true
|
| 955 |
-
}
|
| 956 |
-
},
|
| 957 |
"additional_special_tokens": [
|
| 958 |
"<extra_id_0>",
|
| 959 |
"<extra_id_1>",
|
|
@@ -1072,13 +117,12 @@
|
|
| 1072 |
"<extra_id_114>",
|
| 1073 |
"<extra_id_115>"
|
| 1074 |
],
|
| 1075 |
-
"clean_up_tokenization_spaces": false,
|
| 1076 |
"eos_token": "</s>",
|
| 1077 |
"extra_ids": 116,
|
| 1078 |
-
"extra_special_tokens": {},
|
| 1079 |
-
"mask_token": "<extra_id_0>",
|
| 1080 |
"model_max_length": 1000000000000000019884624838656,
|
|
|
|
| 1081 |
"pad_token": "<pad>",
|
| 1082 |
-
"
|
|
|
|
| 1083 |
"unk_token": "<unk>"
|
| 1084 |
}
|
|
|
|
| 1 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
| 122 |
"model_max_length": 1000000000000000019884624838656,
|
| 123 |
+
"name_or_path": "agemagician/protx-large-1gspan-partreconst-15mlmp-encl48-decl24-ramd128-ranb64-dmodel1536-silu-seq768-tpuv4",
|
| 124 |
"pad_token": "<pad>",
|
| 125 |
+
"special_tokens_map_file": "tokenizer/protein_t5_fast_tokenizer_v4/special_tokens_map.json",
|
| 126 |
+
"tokenizer_class": "T5Tokenizer",
|
| 127 |
"unk_token": "<unk>"
|
| 128 |
}
|