JinghuiLuAstronaut commited on
Commit
15fb628
·
verified ·
1 Parent(s): d4520c3

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md +27 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/INSTALLER +1 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/METADATA +112 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/REQUESTED +0 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/WHEEL +4 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE +3 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE.APACHE +177 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE.BSD +23 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/__init__.py +29 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/configuration_esm.py +280 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/modeling_esm.py +1085 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/tokenization_esm.py +145 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_236000.pt +3 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_304000.pt +3 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_363000.pt +3 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_368000.pt +3 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_430000.pt +3 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_468000.pt +3 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_500000.pt +3 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_537000.pt +3 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/).
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/METADATA ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: packaging
3
+ Version: 26.2
4
+ Summary: Core utilities for Python packages
5
+ Author-email: Donald Stufft <donald@stufft.io>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/x-rst
8
+ License-Expression: Apache-2.0 OR BSD-2-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
23
+ Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient
24
+ Classifier: Typing :: Typed
25
+ License-File: LICENSE
26
+ License-File: LICENSE.APACHE
27
+ License-File: LICENSE.BSD
28
+ Project-URL: Documentation, https://packaging.pypa.io/
29
+ Project-URL: Source, https://github.com/pypa/packaging
30
+
31
+ packaging
32
+ =========
33
+
34
+ .. start-intro
35
+
36
+ Reusable core utilities for various Python Packaging
37
+ `interoperability specifications <https://packaging.python.org/specifications/>`_.
38
+
39
+ This library provides utilities that implement the interoperability
40
+ specifications which have clearly one correct behaviour (eg: :pep:`440`)
41
+ or benefit greatly from having a single shared implementation (eg: :pep:`425`).
42
+
43
+ .. end-intro
44
+
45
+ The ``packaging`` project includes the following: version handling, specifiers,
46
+ markers, requirements, tags, metadata, lockfiles, utilities.
47
+
48
+ Documentation
49
+ -------------
50
+
51
+ The `documentation`_ provides information and the API for the following:
52
+
53
+ - Version Handling
54
+ - Specifiers
55
+ - Markers
56
+ - Licenses
57
+ - Requirements
58
+ - Metadata
59
+ - Tags
60
+ - Lockfiles (pylock)
61
+ - Direct URL helpers
62
+ - Dependency groups
63
+ - Errors
64
+ - Utilities
65
+
66
+ Installation
67
+ ------------
68
+
69
+ Use ``pip`` to install these utilities::
70
+
71
+ pip install packaging
72
+
73
+ The ``packaging`` library uses calendar-based versioning (``YY.N``).
74
+
75
+ Discussion
76
+ ----------
77
+
78
+ If you run into bugs, you can file them in our `issue tracker`_.
79
+
80
+ You can also join discussions on `GitHub Discussions`_ to ask questions or get involved.
81
+
82
+ .. _`documentation`: https://packaging.pypa.io/
83
+ .. _`issue tracker`: https://github.com/pypa/packaging/issues
84
+ .. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions
85
+
86
+
87
+ Code of Conduct
88
+ ---------------
89
+
90
+ Everyone interacting in the packaging project's codebases, issue trackers, chat
91
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
92
+
93
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
94
+
95
+ Contributing
96
+ ------------
97
+
98
+ The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
99
+ well as how to report a potential security issue. The documentation for this
100
+ project also covers information about `project development`_ and `security`_.
101
+
102
+ .. _`project development`: https://packaging.pypa.io/en/latest/development/
103
+ .. _`security`: https://packaging.pypa.io/en/latest/security/
104
+
105
+ Project History
106
+ ---------------
107
+
108
+ Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
109
+ recent changes and project history.
110
+
111
+ .. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
112
+
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/REQUESTED ADDED
File without changes
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ This software is made available under the terms of *either* of the licenses
2
+ found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
3
+ under the terms of *both* these licenses.
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE.APACHE ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/packaging-26.2.dist-info/licenses/LICENSE.BSD ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) Donald Stufft and individual contributors.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_esm import *
22
+ from .modeling_esm import *
23
+ from .modeling_esmfold import *
24
+ from .tokenization_esm import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/configuration_esm.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """ESM model configuration"""
15
+
16
+ from typing import Union
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring, logging
22
+ from ...utils.type_validators import interval, is_divisible_by
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ @strict
29
+ class StructureModuleConfig(PreTrainedConfig):
30
+ """
31
+ Args:
32
+ sequence_dim:
33
+ Single representation channel dimension
34
+ pairwise_dim:
35
+ Pair representation channel dimension
36
+ ipa_dim:
37
+ IPA hidden channel dimension
38
+ resnet_dim:
39
+ Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
40
+ num_heads_ipa:
41
+ Number of IPA heads
42
+ num_qk_points:
43
+ Number of query/key points to generate during IPA
44
+ num_v_points:
45
+ Number of value points to generate during IPA
46
+ dropout_rate:
47
+ Dropout rate used throughout the layer
48
+ num_blocks:
49
+ Number of structure module blocks
50
+ num_transition_layers:
51
+ Number of layers in the single representation transition (Alg. 23 lines 8-9)
52
+ num_resnet_blocks:
53
+ Number of blocks in the angle resnet
54
+ num_angles:
55
+ Number of angles to generate in the angle resnet
56
+ trans_scale_factor:
57
+ Scale of single representation transition hidden dimension
58
+ epsilon:
59
+ Small number used in angle resnet normalization
60
+ inf:
61
+ Large number used for attention masking
62
+ """
63
+
64
+ sequence_dim: int | None = 384
65
+ pairwise_dim: int | None = 128
66
+ ipa_dim: int | None = 16
67
+ resnet_dim: int | None = 128
68
+ num_heads_ipa: int | None = 12
69
+ num_qk_points: int | None = 4
70
+ num_v_points: int | None = 8
71
+ dropout_rate: float | None = 0.1
72
+ num_blocks: int | None = 8
73
+ num_transition_layers: int | None = 1
74
+ num_resnet_blocks: int | None = 2
75
+ num_angles: int | None = 7
76
+ trans_scale_factor: int | None = 10
77
+ epsilon: float | None = 1e-8
78
+ inf: float | None = 1e5
79
+
80
+
81
+ @strict
82
+ class TrunkConfig(PreTrainedConfig):
83
+ sub_configs = {"structure_module": StructureModuleConfig}
84
+
85
+ num_blocks: int | None = 48
86
+ sequence_state_dim: int | None = 1024
87
+ pairwise_state_dim: int | None = is_divisible_by(divisor=2)(default=128)
88
+ sequence_head_width: int | None = 32
89
+ pairwise_head_width: int | None = 32
90
+ position_bins: int | None = 32
91
+ dropout: float | int | None = interval(max=0.4)(default=0.0)
92
+ layer_drop: float | int | None = 0.0
93
+ cpu_grad_checkpoint: bool | None = False
94
+ max_recycles: int | None = interval(min=0)(default=4)
95
+ chunk_size: int | None = 128
96
+ structure_module: Union[dict, "StructureModuleConfig"] | None = None
97
+
98
+ def __post_init__(self, **kwargs):
99
+ if self.structure_module is None:
100
+ self.structure_module = StructureModuleConfig()
101
+ elif isinstance(self.structure_module, dict):
102
+ self.structure_module = StructureModuleConfig(**self.structure_module)
103
+ super().__post_init__(**kwargs)
104
+
105
+ def validate_architecture(self):
106
+ if self.sequence_state_dim % self.sequence_state_dim != 0:
107
+ raise ValueError(
108
+ "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
109
+ f" {self.sequence_state_dim} and {self.sequence_state_dim}."
110
+ )
111
+ if self.pairwise_state_dim % self.pairwise_state_dim != 0:
112
+ raise ValueError(
113
+ "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
114
+ f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
115
+ )
116
+
117
+ sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
118
+ pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width
119
+
120
+ if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
121
+ raise ValueError(
122
+ "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
123
+ f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
124
+ )
125
+ if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
126
+ raise ValueError(
127
+ "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
128
+ f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
129
+ )
130
+
131
+
132
+ @strict
133
+ class EsmFoldConfig(PreTrainedConfig):
134
+ sub_configs = {"trunk": TrunkConfig}
135
+
136
+ esm_type: str | None = None
137
+ fp16_esm: bool | None = True
138
+ use_esm_attn_map: bool | None = False
139
+ esm_ablate_pairwise: bool | None = False
140
+ esm_ablate_sequence: bool | None = False
141
+ esm_input_dropout: float | int | None = 0.0
142
+ embed_aa: bool | None = True
143
+ bypass_lm: bool | None = False
144
+ lddt_head_hid_dim: int | None = 128
145
+ trunk: Union[dict, "TrunkConfig"] | None = None
146
+
147
+ def __post_init__(self, **kwargs):
148
+ if self.trunk is None:
149
+ self.trunk = TrunkConfig()
150
+ elif isinstance(self.trunk, dict):
151
+ self.trunk = TrunkConfig(**self.trunk)
152
+ super().__post_init__(**kwargs)
153
+
154
+
155
+ @auto_docstring(checkpoint="facebook/esm-1b")
156
+ @strict
157
+ class EsmConfig(PreTrainedConfig):
158
+ r"""
159
+ mask_token_id (`int`, *optional*):
160
+ The index of the mask token in the vocabulary. This must be included in the config because of the
161
+ "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
162
+ rope_theta (`float`, defaults to 10000.0):
163
+ The base period of the RoPE embeddings. Only used when `position_embedding_type` is set to `"rotary"`.
164
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
165
+ Type of position embedding. Choose either `"absolute"` or "rotary"`.
166
+ emb_layer_norm_before (`bool`, *optional*):
167
+ Whether to apply layer normalization after embeddings but before the main stem of the network.
168
+ token_dropout (`bool`, defaults to `False`):
169
+ When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
170
+ is_folding_model (`bool`, defaults to `False`):
171
+ When this is enabled, ESMFold model will be initialized.
172
+ esmfold_config (`dict`, *optional*):
173
+ Configuration to initiate the ESMFold module.
174
+ vocab_list (`list`, *optional*):
175
+ List of the vocabulary items.
176
+
177
+ Examples:
178
+
179
+ ```python
180
+ >>> from transformers import EsmModel, EsmConfig
181
+
182
+ >>> # Initializing a ESM facebook/esm-1b style configuration
183
+ >>> configuration = EsmConfig(vocab_size=33)
184
+
185
+ >>> # Initializing a model from the configuration
186
+ >>> model = EsmModel(configuration)
187
+
188
+ >>> # Accessing the model configuration
189
+ >>> configuration = model.config
190
+ ```"""
191
+
192
+ model_type = "esm"
193
+ sub_configs = {"esmfold_config": EsmFoldConfig}
194
+
195
+ vocab_size: int | None = None
196
+ mask_token_id: int | None = None
197
+ pad_token_id: int | None = None
198
+ hidden_size: int = 768
199
+ num_hidden_layers: int = 12
200
+ num_attention_heads: int = 12
201
+ intermediate_size: int = 3072
202
+ hidden_dropout_prob: float | None = 0.1
203
+ attention_probs_dropout_prob: float | None = 0.1
204
+ max_position_embeddings: int = 1026
205
+ rope_theta: float = 10000.0
206
+ initializer_range: float = 0.02
207
+ layer_norm_eps: float | None = 1e-12
208
+ position_embedding_type: str | None = "absolute"
209
+ use_cache: bool = True
210
+ emb_layer_norm_before: bool | None = None
211
+ token_dropout: bool | None = False
212
+ is_folding_model: bool | None = False
213
+ esmfold_config: dict | EsmFoldConfig | None = None
214
+ vocab_list: list[str] | tuple[str, ...] | None = None
215
+ is_decoder: bool | None = False
216
+ add_cross_attention: bool | None = False
217
+ tie_word_embeddings: bool = True
218
+ bos_token_id: int | None = None
219
+ eos_token_id: int | list[int] | None = 2
220
+
221
+ def __post_init__(self, **kwargs):
222
+ if self.is_folding_model:
223
+ if self.esmfold_config is None:
224
+ logger.info("No esmfold_config supplied for folding model, using default values.")
225
+ self.esmfold_config = EsmFoldConfig()
226
+ elif isinstance(self.esmfold_config, dict):
227
+ self.esmfold_config = EsmFoldConfig(**self.esmfold_config)
228
+
229
+ if self.vocab_list is None:
230
+ logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!")
231
+ self.vocab_list = get_default_vocab_list()
232
+ else:
233
+ self.esmfold_config = None
234
+ self.vocab_list = None
235
+
236
+ if self.esmfold_config is not None and getattr(self.esmfold_config, "use_esm_attn_map", False):
237
+ raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!")
238
+
239
+ super().__post_init__(**kwargs)
240
+
241
+
242
+ def get_default_vocab_list():
243
+ return (
244
+ "<cls>",
245
+ "<pad>",
246
+ "<eos>",
247
+ "<unk>",
248
+ "L",
249
+ "A",
250
+ "G",
251
+ "V",
252
+ "S",
253
+ "E",
254
+ "R",
255
+ "T",
256
+ "I",
257
+ "D",
258
+ "P",
259
+ "K",
260
+ "Q",
261
+ "N",
262
+ "F",
263
+ "Y",
264
+ "M",
265
+ "H",
266
+ "W",
267
+ "C",
268
+ "X",
269
+ "B",
270
+ "U",
271
+ "Z",
272
+ "O",
273
+ ".",
274
+ "-",
275
+ "<null_1>",
276
+ "<mask>",
277
+ )
278
+
279
+
280
+ __all__ = ["EsmConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/modeling_esm.py ADDED
@@ -0,0 +1,1085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
2
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch ESM model."""
16
+
17
+ import math
18
+ from collections.abc import Callable
19
+ from typing import Optional
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ... import initialization as init
26
+ from ...integrations import use_kernel_func_from_hub, use_kernelized_func
27
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import (
30
+ BaseModelOutputWithCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ MaskedLMOutput,
33
+ SequenceClassifierOutput,
34
+ TokenClassifierOutput,
35
+ )
36
+ from ...modeling_rope_utils import dynamic_rope_update
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
40
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
41
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
42
+ from .configuration_esm import EsmConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ def rotate_half(x):
49
+ """Rotates half the hidden dims of the input."""
50
+ x1 = x[..., : x.shape[-1] // 2]
51
+ x2 = x[..., x.shape[-1] // 2 :]
52
+ return torch.cat((-x2, x1), dim=-1)
53
+
54
+
55
+ @use_kernel_func_from_hub("rotary_pos_emb")
56
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
57
+ """Applies Rotary Position Embedding to the query and key tensors.
58
+
59
+ Args:
60
+ q (`torch.Tensor`): The query tensor.
61
+ k (`torch.Tensor`): The key tensor.
62
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
63
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
64
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
65
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
66
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
67
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
68
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
69
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
70
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
71
+ Returns:
72
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
73
+ """
74
+ original_dtype = q.dtype
75
+ cos = cos.unsqueeze(unsqueeze_dim)
76
+ sin = sin.unsqueeze(unsqueeze_dim)
77
+ q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
78
+ k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
79
+ return q_embed.to(original_dtype), k_embed.to(original_dtype)
80
+
81
+
82
+ def gelu(x):
83
+ """
84
+ This is the gelu implementation from the original ESM repo. Using F.gelu yields subtly wrong results.
85
+ """
86
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
87
+
88
+
89
+ def symmetrize(x):
90
+ "Make layer symmetric in final two dimensions, used for contact prediction."
91
+ return x + x.transpose(-1, -2)
92
+
93
+
94
+ def average_product_correct(x):
95
+ "Perform average product correct, used for contact prediction."
96
+ a1 = x.sum(-1, keepdims=True)
97
+ a2 = x.sum(-2, keepdims=True)
98
+ a12 = x.sum((-1, -2), keepdims=True)
99
+
100
+ avg = a1 * a2
101
+ avg.div_(a12) # in-place to reduce memory
102
+ normalized = x - avg
103
+ return normalized
104
+
105
+
106
+ class EsmRotaryEmbedding(nn.Module):
107
+ """
108
+ Rotary position embeddings.
109
+ Implementation based on [ModernBERT's RotaryEmbedding](https://github.com/huggingface/transformers/blob/aad13b87ed59f2afcfaebc985f403301887a35fc/src/transformers/models/modernbert/modeling_modernbert.py#L94).
110
+ """
111
+
112
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
113
+
114
+ def __init__(self, config: EsmConfig, device=None):
115
+ super().__init__()
116
+
117
+ self.config = config
118
+ self.rope_type = {}
119
+
120
+ curr_inv_freq, curr_attention_scaling = self.compute_default_rope_parameters(self.config, device)
121
+ self.register_buffer("inv_freq", curr_inv_freq)
122
+ setattr(self, "attention_scaling", curr_attention_scaling)
123
+
124
+ @staticmethod
125
+ def compute_default_rope_parameters(
126
+ config: EsmConfig | None = None,
127
+ device: Optional["torch.device"] = None,
128
+ seq_len: int | None = None,
129
+ ) -> tuple["torch.Tensor", float]:
130
+ """
131
+ Computes the inverse frequencies according to the original RoPE implementation
132
+ Args:
133
+ config ([`~transformers.PreTrainedConfig`]):
134
+ The model configuration.
135
+ device (`torch.device`):
136
+ The device to use for initialization of the inverse frequencies.
137
+ seq_len (`int`, *optional*):
138
+ The current sequence length. Unused for this type of RoPE.
139
+
140
+ Returns:
141
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
142
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
143
+ """
144
+ base = config.rope_theta
145
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
146
+
147
+ attention_factor = 1.0 # Unused in this type of RoPE
148
+
149
+ # Compute the inverse frequencies
150
+ inv_freq = 1.0 / (
151
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
152
+ )
153
+ return inv_freq, attention_factor
154
+
155
+ @torch.no_grad()
156
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
157
+ def forward(self, x, position_ids, layer_type=None):
158
+ inv_freq = getattr(self, "inv_freq")
159
+ attention_scaling = getattr(self, "attention_scaling")
160
+
161
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
165
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
166
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
167
+ emb = torch.cat((freqs, freqs), dim=-1)
168
+ cos = emb.cos() * attention_scaling
169
+ sin = emb.sin() * attention_scaling
170
+
171
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
172
+
173
+
174
+ class EsmContactPredictionHead(nn.Module):
175
+ """Performs symmetrization, apc, and computes a logistic regression on the output features"""
176
+
177
+ def __init__(
178
+ self,
179
+ in_features: int,
180
+ bias=True,
181
+ eos_idx: int = 2,
182
+ ):
183
+ super().__init__()
184
+ self.in_features = in_features
185
+ self.eos_idx = eos_idx
186
+ self.regression = nn.Linear(in_features, 1, bias)
187
+ self.activation = nn.Sigmoid()
188
+
189
+ def forward(self, tokens, attentions):
190
+ # remove eos token attentions
191
+ eos_mask = tokens.ne(self.eos_idx).to(attentions)
192
+ eos_mask = eos_mask.unsqueeze(1) * eos_mask.unsqueeze(2)
193
+ attentions = attentions * eos_mask[:, None, None, :, :]
194
+ attentions = attentions[..., :-1, :-1]
195
+ # remove cls token attentions
196
+ attentions = attentions[..., 1:, 1:]
197
+ batch_size, layers, heads, seqlen, _ = attentions.size()
198
+ attentions = attentions.view(batch_size, layers * heads, seqlen, seqlen)
199
+
200
+ # features: batch x channels x tokens x tokens (symmetric)
201
+ attentions = attentions.to(
202
+ self.regression.weight.device
203
+ ) # attentions always float32, may need to convert to float16
204
+ attentions = average_product_correct(symmetrize(attentions))
205
+ attentions = attentions.permute(0, 2, 3, 1)
206
+ return self.activation(self.regression(attentions).squeeze(3))
207
+
208
+
209
+ class EsmEmbeddings(nn.Module):
210
+ """
211
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
212
+ """
213
+
214
+ def __init__(self, config):
215
+ super().__init__()
216
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
217
+
218
+ if config.emb_layer_norm_before:
219
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
220
+ else:
221
+ self.layer_norm = None
222
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
223
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
224
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
225
+ self.register_buffer(
226
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
227
+ )
228
+
229
+ self.padding_idx = config.pad_token_id
230
+ if self.position_embedding_type == "absolute":
231
+ self.position_embeddings = nn.Embedding(
232
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
233
+ )
234
+ self.token_dropout = config.token_dropout
235
+ self.mask_token_id = config.mask_token_id
236
+
237
+ def forward(
238
+ self,
239
+ input_ids=None,
240
+ attention_mask=None,
241
+ position_ids=None,
242
+ inputs_embeds=None,
243
+ ):
244
+ if position_ids is None:
245
+ if input_ids is not None:
246
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
247
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
248
+ else:
249
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
250
+
251
+ if inputs_embeds is None:
252
+ inputs_embeds = self.word_embeddings(input_ids)
253
+
254
+ # Note that if we want to support ESM-1 (not 1b!) in future then we need to support an
255
+ # embedding_scale factor here.
256
+ embeddings = inputs_embeds
257
+
258
+ # Matt: ESM has the option to handle masking in MLM in a slightly unusual way. If the token_dropout
259
+ # flag is False then it is handled in the same was as BERT/RoBERTa. If it is set to True, however,
260
+ # masked tokens are treated as if they were selected for input dropout and zeroed out.
261
+ # This "mask-dropout" is compensated for when masked tokens are not present, by scaling embeddings by
262
+ # a factor of (fraction of unmasked tokens during training) / (fraction of unmasked tokens in sample).
263
+ # This is analogous to the way that dropout layers scale down outputs during evaluation when not
264
+ # actually dropping out values (or, equivalently, scale up their un-dropped outputs in training).
265
+ if self.token_dropout and input_ids is not None:
266
+ embeddings = embeddings.masked_fill((input_ids == self.mask_token_id).unsqueeze(-1), 0.0)
267
+ mask_ratio_train = 0.15 * 0.8 # Hardcoded as the ratio used in all ESM model training runs
268
+ src_lengths = attention_mask.sum(-1) if attention_mask is not None else input_ids.shape[1]
269
+ mask_ratio_observed = (input_ids == self.mask_token_id).sum(-1).float() / src_lengths
270
+ embeddings = (embeddings * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]).to(
271
+ embeddings.dtype
272
+ )
273
+
274
+ if self.position_embedding_type == "absolute":
275
+ position_embeddings = self.position_embeddings(position_ids)
276
+ embeddings = embeddings + position_embeddings
277
+
278
+ if self.layer_norm is not None:
279
+ embeddings = self.layer_norm(embeddings)
280
+ if attention_mask is not None:
281
+ embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(embeddings.dtype)
282
+ # Matt: I think this line was copied incorrectly from BERT, disabling it for now.
283
+ # embeddings = self.dropout(embeddings)
284
+ return embeddings
285
+
286
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
287
+ """
288
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
289
+
290
+ Args:
291
+ inputs_embeds: torch.Tensor
292
+
293
+ Returns: torch.Tensor
294
+ """
295
+ input_shape = inputs_embeds.size()[:-1]
296
+ sequence_length = input_shape[1]
297
+
298
+ position_ids = torch.arange(
299
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
300
+ )
301
+ return position_ids.unsqueeze(0).expand(input_shape)
302
+
303
+
304
+ # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
305
+ def eager_attention_forward(
306
+ module: nn.Module,
307
+ query: torch.Tensor,
308
+ key: torch.Tensor,
309
+ value: torch.Tensor,
310
+ attention_mask: torch.Tensor | None,
311
+ scaling: float | None = None,
312
+ dropout: float = 0.0,
313
+ **kwargs: Unpack[TransformersKwargs],
314
+ ):
315
+ if scaling is None:
316
+ scaling = query.size(-1) ** -0.5
317
+
318
+ # Take the dot product between "query" and "key" to get the raw attention scores.
319
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
320
+
321
+ if attention_mask is not None:
322
+ attn_weights = attn_weights + attention_mask
323
+
324
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
325
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
326
+
327
+ attn_output = torch.matmul(attn_weights, value)
328
+ attn_output = attn_output.transpose(1, 2).contiguous()
329
+
330
+ return attn_output, attn_weights
331
+
332
+
333
+ @use_kernelized_func(apply_rotary_pos_emb)
334
+ class EsmSelfAttention(nn.Module):
335
+ def __init__(self, config, position_embedding_type=None, layer_idx=None, is_cross_attention=False):
336
+ super().__init__()
337
+ self.config = config
338
+
339
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
340
+ raise ValueError(
341
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
342
+ f"heads ({config.num_attention_heads})"
343
+ )
344
+
345
+ self.num_attention_heads = config.num_attention_heads
346
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
347
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
348
+
349
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
350
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
351
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
352
+
353
+ self.dropout = config.attention_probs_dropout_prob
354
+
355
+ self.position_embedding_type = position_embedding_type or getattr(
356
+ config, "position_embedding_type", "absolute"
357
+ )
358
+ self.scaling = 1.0 # For BC we apply scaling before RoPE
359
+ self.is_decoder = config.is_decoder
360
+ self.layer_idx = layer_idx
361
+ self.is_causal = self.is_decoder and not is_cross_attention
362
+
363
+ def forward(
364
+ self,
365
+ hidden_states: torch.Tensor,
366
+ attention_mask: torch.FloatTensor | None = None,
367
+ encoder_hidden_states: torch.FloatTensor | None = None,
368
+ encoder_attention_mask: torch.FloatTensor | None = None,
369
+ position_embeddings: torch.Tensor | None = None,
370
+ **kwargs: Unpack[TransformersKwargs],
371
+ ) -> tuple[torch.Tensor]:
372
+ input_shape = hidden_states.shape[:-1]
373
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
374
+
375
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
376
+
377
+ is_cross_attention = encoder_hidden_states is not None
378
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
379
+ attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
380
+ key_layer = self.key(current_states).view(hidden_shape).transpose(1, 2)
381
+ value_layer = self.value(current_states).view(hidden_shape).transpose(1, 2)
382
+
383
+ # Matt: Our BERT model (which this code was derived from) scales attention logits down by sqrt(head_dim).
384
+ # ESM scales the query down by the same factor instead. Modulo numerical stability these are equivalent,
385
+ # but not when rotary embeddings get involved. Therefore, we scale the query here to match the original
386
+ # ESM code and fix rotary embeddings.
387
+ query_layer = query_layer * self.attention_head_size**-0.5
388
+
389
+ if self.position_embedding_type == "rotary":
390
+ cos, sin = position_embeddings
391
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, unsqueeze_dim=1)
392
+
393
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
394
+ self.config._attn_implementation, eager_attention_forward
395
+ )
396
+
397
+ attn_output, attn_weights = attention_interface(
398
+ self,
399
+ query_layer,
400
+ key_layer,
401
+ value_layer,
402
+ attention_mask,
403
+ dropout=0.0 if not self.training else self.dropout,
404
+ scaling=self.scaling,
405
+ **kwargs,
406
+ )
407
+
408
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
409
+ return attn_output, attn_weights
410
+
411
+
412
+ class EsmSelfOutput(nn.Module):
413
+ def __init__(self, config):
414
+ super().__init__()
415
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
416
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
417
+
418
+ def forward(self, hidden_states, input_tensor):
419
+ hidden_states = self.dense(hidden_states)
420
+ hidden_states = self.dropout(hidden_states)
421
+ hidden_states = hidden_states + input_tensor
422
+ return hidden_states
423
+
424
+
425
+ class EsmAttention(nn.Module):
426
+ def __init__(self, config, layer_idx=None, is_cross_attention=False):
427
+ super().__init__()
428
+ self.self = EsmSelfAttention(config, layer_idx=layer_idx, is_cross_attention=is_cross_attention)
429
+ self.output = EsmSelfOutput(config)
430
+
431
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
432
+
433
+ def forward(
434
+ self,
435
+ hidden_states,
436
+ attention_mask=None,
437
+ encoder_hidden_states=None,
438
+ encoder_attention_mask=None,
439
+ position_embeddings: torch.Tensor | None = None,
440
+ **kwargs: Unpack[TransformersKwargs],
441
+ ):
442
+ hidden_states_ln = self.LayerNorm(hidden_states)
443
+ attn_output, _ = self.self(
444
+ hidden_states_ln,
445
+ attention_mask=attention_mask,
446
+ encoder_hidden_states=encoder_hidden_states,
447
+ encoder_attention_mask=encoder_attention_mask,
448
+ position_embeddings=position_embeddings,
449
+ **kwargs,
450
+ )
451
+ attn_output = self.output(attn_output, hidden_states)
452
+ return attn_output
453
+
454
+
455
+ class EsmIntermediate(nn.Module):
456
+ def __init__(self, config):
457
+ super().__init__()
458
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
459
+
460
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
461
+ hidden_states = self.dense(hidden_states)
462
+ hidden_states = gelu(hidden_states)
463
+ return hidden_states
464
+
465
+
466
+ class EsmOutput(nn.Module):
467
+ def __init__(self, config):
468
+ super().__init__()
469
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
470
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
471
+
472
+ def forward(self, hidden_states, input_tensor):
473
+ hidden_states = self.dense(hidden_states)
474
+ hidden_states = self.dropout(hidden_states)
475
+ hidden_states = hidden_states + input_tensor
476
+ return hidden_states
477
+
478
+
479
+ class EsmLayer(GradientCheckpointingLayer):
480
+ def __init__(self, config):
481
+ super().__init__()
482
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
483
+ self.seq_len_dim = 1
484
+ self.attention = EsmAttention(config)
485
+ self.is_decoder = config.is_decoder
486
+ self.add_cross_attention = config.add_cross_attention
487
+ if self.add_cross_attention:
488
+ if not self.is_decoder:
489
+ raise RuntimeError(f"{self} should be used as a decoder model if cross attention is added")
490
+ self.crossattention = EsmAttention(config, is_cross_attention=True)
491
+ self.intermediate = EsmIntermediate(config)
492
+ self.output = EsmOutput(config)
493
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states,
498
+ attention_mask=None,
499
+ encoder_hidden_states=None,
500
+ encoder_attention_mask=None,
501
+ position_embeddings: torch.Tensor | None = None,
502
+ **kwargs: Unpack[TransformersKwargs],
503
+ ):
504
+ attention_output = self.attention(
505
+ hidden_states,
506
+ attention_mask=attention_mask,
507
+ position_embeddings=position_embeddings,
508
+ **kwargs,
509
+ )
510
+
511
+ if self.is_decoder and encoder_hidden_states is not None:
512
+ if not hasattr(self, "crossattention"):
513
+ raise AttributeError(
514
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated"
515
+ " with cross-attention layers by setting `config.add_cross_attention=True`"
516
+ )
517
+
518
+ attention_output = self.crossattention(
519
+ attention_output,
520
+ attention_mask=attention_mask,
521
+ encoder_hidden_states=encoder_hidden_states,
522
+ encoder_attention_mask=encoder_attention_mask,
523
+ position_embeddings=position_embeddings,
524
+ **kwargs,
525
+ )
526
+
527
+ layer_output = self.feed_forward_chunk(attention_output)
528
+ return layer_output
529
+
530
+ def feed_forward_chunk(self, attention_output):
531
+ attention_output_ln = self.LayerNorm(attention_output)
532
+ intermediate_output = self.intermediate(attention_output_ln)
533
+ layer_output = self.output(intermediate_output, attention_output)
534
+ return layer_output
535
+
536
+
537
+ class EsmEncoder(nn.Module):
538
+ def __init__(self, config):
539
+ super().__init__()
540
+ self.config = config
541
+ self.layer = nn.ModuleList([EsmLayer(config) for _ in range(config.num_hidden_layers)])
542
+ self.emb_layer_norm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
543
+ self.gradient_checkpointing = False
544
+
545
+ @can_return_tuple
546
+ def forward(
547
+ self,
548
+ hidden_states,
549
+ attention_mask=None,
550
+ encoder_hidden_states=None,
551
+ encoder_attention_mask=None,
552
+ position_embeddings: torch.Tensor | None = None,
553
+ **kwargs: Unpack[TransformersKwargs],
554
+ ):
555
+ for i, layer_module in enumerate(self.layer):
556
+ hidden_states = layer_module(
557
+ hidden_states,
558
+ attention_mask=attention_mask,
559
+ encoder_hidden_states=encoder_hidden_states,
560
+ encoder_attention_mask=encoder_attention_mask,
561
+ position_embeddings=position_embeddings,
562
+ **kwargs,
563
+ )
564
+
565
+ if self.emb_layer_norm_after:
566
+ hidden_states = self.emb_layer_norm_after(hidden_states)
567
+
568
+ return BaseModelOutputWithCrossAttentions(last_hidden_state=hidden_states)
569
+
570
+
571
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
572
+ class EsmPooler(nn.Module):
573
+ def __init__(self, config):
574
+ super().__init__()
575
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
576
+ self.activation = nn.Tanh()
577
+
578
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
579
+ # We "pool" the model by simply taking the hidden state corresponding
580
+ # to the first token.
581
+ first_token_tensor = hidden_states[:, 0]
582
+ pooled_output = self.dense(first_token_tensor)
583
+ pooled_output = self.activation(pooled_output)
584
+ return pooled_output
585
+
586
+
587
+ @auto_docstring
588
+ class EsmPreTrainedModel(PreTrainedModel):
589
+ config: EsmConfig
590
+ base_model_prefix = "esm"
591
+ supports_gradient_checkpointing = True
592
+ accepts_loss_kwargs = False
593
+ _no_split_modules = ["EsmLayer", "EsmFoldTriangularSelfAttentionBlock", "EsmEmbeddings"]
594
+ _keys_to_ignore_on_load_unexpected = ["position_embeddings.weight"]
595
+ _supports_flash_attn = True
596
+ _supports_sdpa = True
597
+ _supports_flex_attn = True
598
+ _supports_attention_backend = True
599
+
600
+ _can_record_outputs = {
601
+ "hidden_states": EsmLayer,
602
+ "attentions": [OutputRecorder(EsmSelfAttention, index=1, layer_name="attention")],
603
+ "cross_attentions": [
604
+ OutputRecorder(EsmSelfAttention, index=1, layer_name="crossattention"),
605
+ ],
606
+ }
607
+
608
+ @torch.no_grad()
609
+ def _init_weights(self, module):
610
+ """Initialize the weights"""
611
+ super()._init_weights(module)
612
+ if isinstance(module, EsmLMHead):
613
+ init.zeros_(module.bias)
614
+ elif isinstance(module, EsmEmbeddings):
615
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
616
+ elif isinstance(module, EsmRotaryEmbedding):
617
+ curr_inv_freq, _ = module.compute_default_rope_parameters(module.config)
618
+ init.copy_(getattr(module, "inv_freq"), curr_inv_freq)
619
+
620
+ def get_output_embeddings(self):
621
+ # NOTE: get_output_embeddings() must return None to prevent accidental weight tying.
622
+ # See e.g. https://github.com/huggingface/transformers/pull/39339#discussion_r2219126400
623
+ return None
624
+
625
+
626
+ @auto_docstring
627
+ class EsmModel(EsmPreTrainedModel):
628
+ """
629
+
630
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
631
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
632
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
633
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
634
+
635
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
636
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
637
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
638
+ """
639
+
640
+ def __init__(self, config, add_pooling_layer=True):
641
+ r"""
642
+ add_pooling_layer (bool, *optional*, defaults to `True`):
643
+ Whether to add a pooling layer
644
+ """
645
+ super().__init__(config)
646
+ self.config = config
647
+
648
+ self.embeddings = EsmEmbeddings(config)
649
+
650
+ self.rotary_embeddings = None
651
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
652
+ if self.position_embedding_type == "rotary":
653
+ self.rotary_embeddings = EsmRotaryEmbedding(config=config)
654
+
655
+ self.encoder = EsmEncoder(config)
656
+
657
+ self.pooler = EsmPooler(config) if add_pooling_layer else None
658
+
659
+ self.contact_head = EsmContactPredictionHead(
660
+ in_features=config.num_hidden_layers * config.num_attention_heads, bias=True
661
+ )
662
+
663
+ self._register_load_state_dict_pre_hook(self.load_hook)
664
+ # Initialize weights and apply final processing
665
+ self.post_init()
666
+
667
+ def load_hook(self, state_dict, prefix, *args):
668
+ """Remap per-layer rotary inv_freq keys from old checkpoints to the new model-level location.
669
+
670
+ Old checkpoints stored inv_freq per attention layer at:
671
+ {prefix}encoder.layer.{i}.attention.self.rotary_embeddings.inv_freq
672
+ New code stores a single shared inv_freq at:
673
+ {prefix}rotary_embeddings.inv_freq
674
+ The old checkpoint values must be preserved (not recomputed) because they may
675
+ have been saved in float16, matching the precision used during training.
676
+ """
677
+ new_key = f"{prefix}rotary_embeddings.inv_freq"
678
+ if new_key not in state_dict:
679
+ old_keys = sorted(
680
+ k
681
+ for k in list(state_dict.keys())
682
+ if k.startswith(prefix) and k.endswith(".attention.self.rotary_embeddings.inv_freq")
683
+ )
684
+ if old_keys:
685
+ state_dict[new_key] = state_dict[old_keys[0]]
686
+ for k in old_keys:
687
+ del state_dict[k]
688
+
689
+ def get_input_embeddings(self):
690
+ return self.embeddings.word_embeddings
691
+
692
+ def set_input_embeddings(self, value):
693
+ self.embeddings.word_embeddings = value
694
+
695
+ @merge_with_config_defaults
696
+ @capture_outputs
697
+ @auto_docstring
698
+ def forward(
699
+ self,
700
+ input_ids: torch.Tensor | None = None,
701
+ attention_mask: torch.Tensor | None = None,
702
+ position_ids: torch.Tensor | None = None,
703
+ inputs_embeds: torch.Tensor | None = None,
704
+ encoder_hidden_states: torch.Tensor | None = None,
705
+ encoder_attention_mask: torch.Tensor | None = None,
706
+ **kwargs: Unpack[TransformersKwargs],
707
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
708
+ r"""
709
+ input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length))`):
710
+ Indices of input sequence tokens in the vocabulary.
711
+
712
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
713
+ [`PreTrainedTokenizer.__call__`] for details.
714
+
715
+ [What are input IDs?](../glossary#input-ids)
716
+ position_ids (`torch.LongTensor` of shape `((batch_size, sequence_length))`, *optional*):
717
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
718
+ config.max_position_embeddings - 1]`.
719
+
720
+ [What are position IDs?](../glossary#position-ids)
721
+ inputs_embeds (`torch.FloatTensor` of shape `((batch_size, sequence_length), hidden_size)`, *optional*):
722
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
723
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
724
+ model's internal embedding lookup matrix.
725
+ """
726
+ if (input_ids is None) ^ (inputs_embeds is not None):
727
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
728
+
729
+ if inputs_embeds is None:
730
+ # Important, attention_mask must be passed to the embedding class
731
+ # This effects how the token_dropout is calculated
732
+ inputs_embeds = self.embeddings(
733
+ input_ids=input_ids,
734
+ attention_mask=attention_mask,
735
+ position_ids=position_ids,
736
+ )
737
+
738
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
739
+ attention_mask=attention_mask,
740
+ encoder_attention_mask=encoder_attention_mask,
741
+ embedding_output=inputs_embeds,
742
+ encoder_hidden_states=encoder_hidden_states,
743
+ past_key_values=None,
744
+ )
745
+
746
+ if self.position_embedding_type == "rotary":
747
+ if position_ids is None:
748
+ seq_len = inputs_embeds.shape[1]
749
+ position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0)
750
+ position_embeddings = self.rotary_embeddings(inputs_embeds, position_ids)
751
+ else:
752
+ position_embeddings = None
753
+
754
+ encoder_outputs = self.encoder(
755
+ inputs_embeds,
756
+ attention_mask=attention_mask,
757
+ encoder_hidden_states=encoder_hidden_states,
758
+ encoder_attention_mask=encoder_attention_mask,
759
+ position_embeddings=position_embeddings,
760
+ **kwargs,
761
+ )
762
+ sequence_output = encoder_outputs[0]
763
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
764
+
765
+ return BaseModelOutputWithPoolingAndCrossAttentions(
766
+ last_hidden_state=sequence_output,
767
+ pooler_output=pooled_output,
768
+ )
769
+
770
+ # Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks
771
+ def _create_attention_masks(
772
+ self,
773
+ attention_mask,
774
+ encoder_attention_mask,
775
+ embedding_output,
776
+ encoder_hidden_states,
777
+ past_key_values,
778
+ ):
779
+ if self.config.is_decoder:
780
+ attention_mask = create_causal_mask(
781
+ config=self.config,
782
+ inputs_embeds=embedding_output,
783
+ attention_mask=attention_mask,
784
+ past_key_values=past_key_values,
785
+ )
786
+ else:
787
+ attention_mask = create_bidirectional_mask(
788
+ config=self.config,
789
+ inputs_embeds=embedding_output,
790
+ attention_mask=attention_mask,
791
+ )
792
+
793
+ if encoder_attention_mask is not None:
794
+ encoder_attention_mask = create_bidirectional_mask(
795
+ config=self.config,
796
+ inputs_embeds=embedding_output,
797
+ attention_mask=encoder_attention_mask,
798
+ encoder_hidden_states=encoder_hidden_states,
799
+ )
800
+
801
+ return attention_mask, encoder_attention_mask
802
+
803
+ def predict_contacts(self, tokens, attention_mask):
804
+ attns = self(tokens, attention_mask=attention_mask, return_dict=True, output_attentions=True).attentions
805
+ attns = torch.stack(attns, dim=1) # Matches the original model layout
806
+ # In the original model, attentions for padding tokens are completely zeroed out.
807
+ # This makes no difference most of the time because the other tokens won't attend to them,
808
+ # but it does for the contact prediction task, which takes attentions as input,
809
+ # so we have to mimic that here.
810
+ attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3)
811
+ attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4)
812
+ return self.contact_head(tokens, attns)
813
+
814
+
815
+ @auto_docstring
816
+ class EsmForMaskedLM(EsmPreTrainedModel):
817
+ _tied_weights_keys = {"lm_head.decoder.weight": "esm.embeddings.word_embeddings.weight"}
818
+
819
+ def __init__(self, config):
820
+ super().__init__(config)
821
+
822
+ if config.is_decoder:
823
+ logger.warning(
824
+ "If you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for "
825
+ "bi-directional self-attention."
826
+ )
827
+
828
+ self.esm = EsmModel(config, add_pooling_layer=False)
829
+ self.lm_head = EsmLMHead(config)
830
+
831
+ self.post_init()
832
+
833
+ def get_output_embeddings(self):
834
+ return self.lm_head.decoder
835
+
836
+ def set_output_embeddings(self, new_embeddings):
837
+ self.lm_head.decoder = new_embeddings
838
+
839
+ @can_return_tuple
840
+ @auto_docstring
841
+ def forward(
842
+ self,
843
+ input_ids: torch.LongTensor | None = None,
844
+ attention_mask: torch.Tensor | None = None,
845
+ position_ids: torch.LongTensor | None = None,
846
+ inputs_embeds: torch.FloatTensor | None = None,
847
+ encoder_hidden_states: torch.FloatTensor | None = None,
848
+ encoder_attention_mask: torch.Tensor | None = None,
849
+ labels: torch.LongTensor | None = None,
850
+ **kwargs: Unpack[TransformersKwargs],
851
+ ) -> tuple | MaskedLMOutput:
852
+ r"""
853
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
854
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
855
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
856
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
857
+ """
858
+
859
+ outputs = self.esm(
860
+ input_ids,
861
+ attention_mask=attention_mask,
862
+ position_ids=position_ids,
863
+ inputs_embeds=inputs_embeds,
864
+ encoder_hidden_states=encoder_hidden_states,
865
+ encoder_attention_mask=encoder_attention_mask,
866
+ **kwargs,
867
+ )
868
+ sequence_output = outputs[0]
869
+ prediction_scores = self.lm_head(sequence_output)
870
+
871
+ masked_lm_loss = None
872
+ if labels is not None:
873
+ loss_fct = CrossEntropyLoss()
874
+
875
+ labels = labels.to(prediction_scores.device)
876
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
877
+
878
+ return MaskedLMOutput(
879
+ loss=masked_lm_loss,
880
+ logits=prediction_scores,
881
+ hidden_states=outputs.hidden_states,
882
+ attentions=outputs.attentions,
883
+ )
884
+
885
+ def predict_contacts(self, tokens, attention_mask):
886
+ return self.esm.predict_contacts(tokens, attention_mask=attention_mask)
887
+
888
+
889
+ class EsmLMHead(nn.Module):
890
+ """ESM Head for masked language modeling."""
891
+
892
+ def __init__(self, config):
893
+ super().__init__()
894
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
895
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
896
+
897
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
898
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
899
+
900
+ def forward(self, features, **kwargs):
901
+ x = self.dense(features)
902
+ x = gelu(x)
903
+ x = self.layer_norm(x)
904
+
905
+ # project back to size of vocabulary with bias
906
+ x = self.decoder(x) + self.bias
907
+ return x
908
+
909
+
910
+ @auto_docstring(
911
+ custom_intro="""
912
+ ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
913
+ output) e.g. for GLUE tasks.
914
+ """
915
+ )
916
+ class EsmForSequenceClassification(EsmPreTrainedModel):
917
+ def __init__(self, config):
918
+ super().__init__(config)
919
+ self.num_labels = config.num_labels
920
+ self.config = config
921
+
922
+ self.esm = EsmModel(config, add_pooling_layer=False)
923
+ self.classifier = EsmClassificationHead(config)
924
+
925
+ self.post_init()
926
+
927
+ @can_return_tuple
928
+ @auto_docstring
929
+ def forward(
930
+ self,
931
+ input_ids: torch.LongTensor | None = None,
932
+ attention_mask: torch.Tensor | None = None,
933
+ position_ids: torch.LongTensor | None = None,
934
+ inputs_embeds: torch.FloatTensor | None = None,
935
+ labels: torch.LongTensor | None = None,
936
+ **kwargs: Unpack[TransformersKwargs],
937
+ ) -> tuple | SequenceClassifierOutput:
938
+ r"""
939
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
940
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
941
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
942
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
943
+ """
944
+
945
+ outputs = self.esm(
946
+ input_ids,
947
+ attention_mask=attention_mask,
948
+ position_ids=position_ids,
949
+ inputs_embeds=inputs_embeds,
950
+ **kwargs,
951
+ )
952
+ sequence_output = outputs[0]
953
+ logits = self.classifier(sequence_output)
954
+
955
+ loss = None
956
+ if labels is not None:
957
+ labels = labels.to(logits.device)
958
+
959
+ if self.config.problem_type is None:
960
+ if self.num_labels == 1:
961
+ self.config.problem_type = "regression"
962
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
963
+ self.config.problem_type = "single_label_classification"
964
+ else:
965
+ self.config.problem_type = "multi_label_classification"
966
+
967
+ if self.config.problem_type == "regression":
968
+ loss_fct = MSELoss()
969
+ if self.num_labels == 1:
970
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
971
+ else:
972
+ loss = loss_fct(logits, labels)
973
+ elif self.config.problem_type == "single_label_classification":
974
+ loss_fct = CrossEntropyLoss()
975
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
976
+ elif self.config.problem_type == "multi_label_classification":
977
+ loss_fct = BCEWithLogitsLoss()
978
+ loss = loss_fct(logits, labels)
979
+
980
+ return SequenceClassifierOutput(
981
+ loss=loss,
982
+ logits=logits,
983
+ hidden_states=outputs.hidden_states,
984
+ attentions=outputs.attentions,
985
+ )
986
+
987
+
988
+ @auto_docstring
989
+ class EsmForTokenClassification(EsmPreTrainedModel):
990
+ def __init__(self, config):
991
+ super().__init__(config)
992
+ self.num_labels = config.num_labels
993
+
994
+ self.esm = EsmModel(config, add_pooling_layer=False)
995
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
996
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
997
+
998
+ self.post_init()
999
+
1000
+ @can_return_tuple
1001
+ @auto_docstring
1002
+ def forward(
1003
+ self,
1004
+ input_ids: torch.LongTensor | None = None,
1005
+ attention_mask: torch.Tensor | None = None,
1006
+ position_ids: torch.LongTensor | None = None,
1007
+ inputs_embeds: torch.FloatTensor | None = None,
1008
+ labels: torch.LongTensor | None = None,
1009
+ **kwargs: Unpack[TransformersKwargs],
1010
+ ) -> tuple | TokenClassifierOutput:
1011
+ r"""
1012
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1013
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1014
+ """
1015
+
1016
+ outputs = self.esm(
1017
+ input_ids,
1018
+ attention_mask=attention_mask,
1019
+ position_ids=position_ids,
1020
+ inputs_embeds=inputs_embeds,
1021
+ **kwargs,
1022
+ )
1023
+
1024
+ sequence_output = outputs[0]
1025
+
1026
+ sequence_output = self.dropout(sequence_output)
1027
+ logits = self.classifier(sequence_output)
1028
+
1029
+ loss = None
1030
+ if labels is not None:
1031
+ loss_fct = CrossEntropyLoss()
1032
+
1033
+ labels = labels.to(logits.device)
1034
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1035
+
1036
+ return TokenClassifierOutput(
1037
+ loss=loss,
1038
+ logits=logits,
1039
+ hidden_states=outputs.hidden_states,
1040
+ attentions=outputs.attentions,
1041
+ )
1042
+
1043
+
1044
+ class EsmClassificationHead(nn.Module):
1045
+ """Head for sentence-level classification tasks."""
1046
+
1047
+ def __init__(self, config):
1048
+ super().__init__()
1049
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1050
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1051
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1052
+
1053
+ def forward(self, features, **kwargs):
1054
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1055
+ x = self.dropout(x)
1056
+ x = self.dense(x)
1057
+ x = torch.tanh(x)
1058
+ x = self.dropout(x)
1059
+ x = self.out_proj(x)
1060
+ return x
1061
+
1062
+
1063
+ def create_position_ids_from_input_ids(input_ids, padding_idx):
1064
+ """
1065
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1066
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1067
+
1068
+ Args:
1069
+ x: torch.Tensor x:
1070
+
1071
+ Returns: torch.Tensor
1072
+ """
1073
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1074
+ mask = input_ids.ne(padding_idx).int()
1075
+ incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
1076
+ return incremental_indices.long() + padding_idx
1077
+
1078
+
1079
+ __all__ = [
1080
+ "EsmForMaskedLM",
1081
+ "EsmForSequenceClassification",
1082
+ "EsmForTokenClassification",
1083
+ "EsmModel",
1084
+ "EsmPreTrainedModel",
1085
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/esm/tokenization_esm.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes for ESM."""
15
+
16
+ import os
17
+
18
+ from ...tokenization_python import PreTrainedTokenizer
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
25
+
26
+
27
+ def load_vocab_file(vocab_file):
28
+ with open(vocab_file, "r") as f:
29
+ lines = f.read().splitlines()
30
+ return [l.strip() for l in lines]
31
+
32
+
33
+ class EsmTokenizer(PreTrainedTokenizer):
34
+ """
35
+ Constructs an ESM tokenizer.
36
+ """
37
+
38
+ vocab_files_names = VOCAB_FILES_NAMES
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_file,
44
+ unk_token="<unk>",
45
+ cls_token="<cls>",
46
+ pad_token="<pad>",
47
+ mask_token="<mask>",
48
+ eos_token="<eos>",
49
+ **kwargs,
50
+ ):
51
+ self.all_tokens = load_vocab_file(vocab_file)
52
+ self._id_to_token = dict(enumerate(self.all_tokens))
53
+ self._token_to_id = {tok: ind for ind, tok in enumerate(self.all_tokens)}
54
+ super().__init__(
55
+ unk_token=unk_token,
56
+ cls_token=cls_token,
57
+ pad_token=pad_token,
58
+ mask_token=mask_token,
59
+ eos_token=eos_token,
60
+ **kwargs,
61
+ )
62
+
63
+ # TODO, all the tokens are added? But they are also part of the vocab... bit strange.
64
+ # none of them are special, but they all need special splitting.
65
+
66
+ self.unique_no_split_tokens = self.all_tokens
67
+ self._update_trie(self.unique_no_split_tokens)
68
+
69
+ def _convert_id_to_token(self, index: int) -> str:
70
+ return self._id_to_token.get(index, self.unk_token)
71
+
72
+ def _convert_token_to_id(self, token: str) -> int:
73
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
74
+
75
+ def _tokenize(self, text, **kwargs):
76
+ return text.split()
77
+
78
+ def get_vocab(self):
79
+ base_vocab = self._token_to_id.copy()
80
+ base_vocab.update(self.added_tokens_encoder)
81
+ return base_vocab
82
+
83
+ def token_to_id(self, token: str) -> int:
84
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
85
+
86
+ def id_to_token(self, index: int) -> str:
87
+ return self._id_to_token.get(index, self.unk_token)
88
+
89
+ def build_inputs_with_special_tokens(
90
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
91
+ ) -> list[int]:
92
+ cls = [self.cls_token_id]
93
+ sep = [self.eos_token_id] # No sep token in ESM vocabulary
94
+ if token_ids_1 is None:
95
+ if self.eos_token_id is None:
96
+ return cls + token_ids_0
97
+ else:
98
+ return cls + token_ids_0 + sep
99
+ elif self.eos_token_id is None:
100
+ raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!")
101
+ return cls + token_ids_0 + sep + token_ids_1 + sep # Multiple inputs always have an EOS token
102
+
103
+ def get_special_tokens_mask(
104
+ self, token_ids_0: list, token_ids_1: list | None = None, already_has_special_tokens: bool = False
105
+ ) -> list[int]:
106
+ """
107
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
108
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
109
+
110
+ Args:
111
+ token_ids_0 (`list[int]`):
112
+ List of ids of the first sequence.
113
+ token_ids_1 (`list[int]`, *optional*):
114
+ List of ids of the second sequence.
115
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
116
+ Whether or not the token list is already formatted with special tokens for the model.
117
+
118
+ Returns:
119
+ A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
120
+ """
121
+ if already_has_special_tokens:
122
+ if token_ids_1 is not None:
123
+ raise ValueError(
124
+ "You should not supply a second sequence if the provided sequence of "
125
+ "ids is already formatted with special tokens for the model."
126
+ )
127
+
128
+ return [1 if token in self.all_special_ids else 0 for token in token_ids_0]
129
+ mask = [1] + ([0] * len(token_ids_0)) + [1]
130
+ if token_ids_1 is not None:
131
+ mask += [0] * len(token_ids_1) + [1]
132
+ return mask
133
+
134
+ def save_vocabulary(self, save_directory, filename_prefix):
135
+ vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.txt")
136
+ with open(vocab_file, "w") as f:
137
+ f.write("\n".join(self.all_tokens))
138
+ return (vocab_file,)
139
+
140
+ @property
141
+ def vocab_size(self) -> int:
142
+ return len(self.all_tokens)
143
+
144
+
145
+ __all__ = ["EsmTokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_236000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:254d33560ad231355d5418eb2bdb93c9d6481b3d3f50674ed8c126edaa156080
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_304000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2fa8e1a59f04f315d79ddf5da5f8b04142baa1123f52679df089b0c6167502b
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_363000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f9fb40f2b30528d780dd84e2727e6d23702ae2ef1cc1a9c21c5869ad8c48ba9
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_368000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b69b5660dd43ffd7328bcf09b483186ec983103583c751f8ba4a9701a951551c
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_430000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f340203e28326b1b64ada7303f429831726788b275cf1c23bc816f1af26ff0e8
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_468000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0a0df0e9ed61684dab771d2309f7ec3ab387522eaca00fa48929d3d4c6e864d
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_500000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a3fca4e5bce023e557784f4753ea74684b06f383c43d625c200bd5b91dbc40d
3
+ size 962143586
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck256_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_050225/step_537000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f62d465556121a4012045ce1d205f81df5f551206c02ef6d892037000f4ed21b
3
+ size 962143586