LevelCapTech commited on
Commit
ec8ffde
·
verified ·
1 Parent(s): 298476e

Publish experimental Stage 2 model built on Hugging Face Jobs

Browse files
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": true,
4
+ "pooling_mode_mean_tokens": false,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LevelCapTech (fine-tuning modifications)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LICENSE-APACHE-2.0 ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,102 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ license: mit
5
+ library_name: sentence-transformers
6
+ base_model: nomic-ai/CodeRankEmbed
7
+ pipeline_tag: feature-extraction
8
+ tags:
9
+ - python
10
+ - fault-localization
11
+ - code-retrieval
12
+ - experimental
13
+ - safetensors
14
  ---
15
+
16
+ # FailureLens: experimental fault-localization encoder
17
+
18
+ This is a **trained experimental model**, rebuilt on Hugging Face Jobs from
19
+ the FailureLens Stage 2 recipe. Given a Python traceback and candidate function
20
+ source texts, it supplies embeddings for cosine-similarity ranking.
21
+
22
+ **Independent held-out evaluation (Gate C) is pending. No improvement over the
23
+ shipped baseline or the base encoder has been established. This release is for
24
+ experimentation, not evidence of production readiness or agent adoption.**
25
+
26
+ ## Use
27
+
28
+ Install PyTorch 2.11.0, transformers 5.22.0, sentence-transformers 6.2.0,
29
+ safetensors 0.8.0 and einops 0.8.1. The model contains NomicBERT custom Python
30
+ code from the pinned base, with a documented transformers-5 attention-mask fix.
31
+ Review that code before enabling `trust_remote_code`. This example pins the
32
+ model revision and uses only safetensors weights.
33
+
34
+ ```python
35
+ from huggingface_hub import HfApi
36
+ from sentence_transformers import SentenceTransformer
37
+
38
+ revision = HfApi().model_info("LevelCapTech/failurelens").sha
39
+ model = SentenceTransformer(
40
+ "LevelCapTech/failurelens",
41
+ revision=revision,
42
+ trust_remote_code=True,
43
+ device="cpu",
44
+ model_kwargs={"use_safetensors": True},
45
+ )
46
+ error_log = "ZeroDivisionError: division by zero"
47
+ candidates = [
48
+ "def average(values): return sum(values) / len(values)",
49
+ "def greet(name): return 'Hello ' + name",
50
+ ]
51
+ # Stage 2 uses the stripped traceback directly, without a query prefix.
52
+ query = model.encode([error_log.strip()], normalize_embeddings=True)
53
+ code = model.encode(candidates, normalize_embeddings=True)
54
+ scores = (query @ code.T)[0]
55
+ ranked_indices = sorted(range(len(candidates)), key=lambda i: (-float(scores[i]), i))
56
+ print([(i, float(scores[i])) for i in ranked_indices])
57
+ ```
58
+
59
+ Scores are similarities, not probabilities. Callers supply the candidate pool;
60
+ this encoder does not locate files, invent line numbers, or generate fixes.
61
+ The current FailureLens library's generic `from_pretrained` path has a different
62
+ query transform and a restricted custom-code allowlist. The standalone example
63
+ above is the supported interface for this experimental release.
64
+
65
+ ## Training and limitations
66
+
67
+ - Base: `nomic-ai/CodeRankEmbed` at `3c4b60807d71f79b43f3c4363786d9493691f8b1` (MIT).
68
+ - 136,731,648 parameters; only the final encoder block (9,440,256 parameters)
69
+ is fine-tuned, with per-triplet InfoNCE and cosine similarity.
70
+ - 12 private, sanitized synthetic examples: 6 train from `pallets/click` and
71
+ 6 validation from `python-attrs/attrs`; source repositories are disjoint.
72
+ - Seed 42, 3 epochs, batch size 2, AdamW, learning rate 2e-5, weight decay 0.01,
73
+ temperature 0.07, cosine learning-rate schedule. CLS pooling is retained.
74
+ - Effective model sequence limit: 8192 tokens.
75
+ The legacy config's `max_length=512` is not applied by the training function;
76
+ the effective limit and observed feature lengths are recorded in provenance.
77
+ - Built on Tesla T4. This cloud
78
+ rebuild has its own checksum; it is not claimed bit-identical to local v3.
79
+ - Validation losses only reflect this tiny synthetic set. No natural-bug,
80
+ multilingual, latency-budget, or independent accuracy claim is made.
81
+ - Baseline retrieval can omit the actual cause; reranking cannot recover an
82
+ omitted function. Python traceback support in the library remains limited.
83
+
84
+ ## Reproducibility and distribution
85
+
86
+ The Job fetched pinned public source and base weights, trained, assembled and
87
+ tested the model, and uploaded the weights directly to the Hub. The submitting
88
+ connection sent only this build script and approximately 6 KB of compressed
89
+ training features as an encrypted Job secret. Private records, features,
90
+ optimizer checkpoints and held-out labels are not distributed here.
91
+
92
+ - Job: https://huggingface.co/jobs/LevelCapTech/6ae7d7a8c78863f9c62ff0e8
93
+ - Training source: https://github.com/LevelCapTech/FailureLens/tree/2985bfcfbf5bf79bc3b3b0589284f6a4ca481970
94
+ - Weights SHA-256: `8e8fb971f8c1dce22ae29ea4f682cb8387790ad608e06d3800b62d3413a0a9e4`
95
+ - Data SHA-256: `74909f51b588c311de798bee29b748cfc1ead65fd2948053c8f3a1c729e465c1`
96
+ - Exact dependencies, training history, code hashes and smoke checks:
97
+ [failurelens_provenance.json](failurelens_provenance.json).
98
+
99
+ The weights are distributed under MIT, as declared by the base model.
100
+ Upstream code retains its copyright headers and license notices; see
101
+ [LICENSE](LICENSE) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
102
+ FailureLens's repository source and build script are Apache-2.0.
THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ Base model: nomic-ai/CodeRankEmbed @ 3c4b60807d71f79b43f3c4363786d9493691f8b1; the upstream model card declares MIT.
4
+ Original model-code copyright headers are preserved.
5
+
6
+
7
+ ## Upstream notice: pallets/click
8
+
9
+ Source: https://raw.githubusercontent.com/pallets/click/2247b35ea1c47c727d7a06e51fa280e12a863ff6/LICENSE.txt
10
+
11
+ ```text
12
+ Copyright 2014 Pallets
13
+
14
+ Redistribution and use in source and binary forms, with or without
15
+ modification, are permitted provided that the following conditions are
16
+ met:
17
+
18
+ 1. Redistributions of source code must retain the above copyright
19
+ notice, this list of conditions and the following disclaimer.
20
+
21
+ 2. Redistributions in binary form must reproduce the above copyright
22
+ notice, this list of conditions and the following disclaimer in the
23
+ documentation and/or other materials provided with the distribution.
24
+
25
+ 3. Neither the name of the copyright holder nor the names of its
26
+ contributors may be used to endorse or promote products derived from
27
+ this software without specific prior written permission.
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
32
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
35
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
36
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
37
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
38
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
39
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40
+
41
+ ```
42
+
43
+ ## Upstream notice: python-attrs/attrs
44
+
45
+ Source: https://raw.githubusercontent.com/python-attrs/attrs/c8bb9bfaa2843e7844b5bb13bed4370b51feec4f/LICENSE
46
+
47
+ ```text
48
+ The MIT License (MIT)
49
+
50
+ Copyright (c) 2015 Hynek Schlawack and the attrs contributors
51
+
52
+ Permission is hereby granted, free of charge, to any person obtaining a copy
53
+ of this software and associated documentation files (the "Software"), to deal
54
+ in the Software without restriction, including without limitation the rights
55
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
56
+ copies of the Software, and to permit persons to whom the Software is
57
+ furnished to do so, subject to the following conditions:
58
+
59
+ The above copyright notice and this permission notice shall be included in all
60
+ copies or substantial portions of the Software.
61
+
62
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
63
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
64
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
65
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
66
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
67
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
68
+ SOFTWARE.
69
+
70
+ ```
71
+
72
+ ## Upstream notice: Dao-AILab/flash-attention
73
+
74
+ Source: https://raw.githubusercontent.com/Dao-AILab/flash-attention/main/LICENSE
75
+
76
+ ```text
77
+ BSD 3-Clause License
78
+
79
+ Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
80
+ All rights reserved.
81
+
82
+ Redistribution and use in source and binary forms, with or without
83
+ modification, are permitted provided that the following conditions are met:
84
+
85
+ * Redistributions of source code must retain the above copyright notice, this
86
+ list of conditions and the following disclaimer.
87
+
88
+ * Redistributions in binary form must reproduce the above copyright notice,
89
+ this list of conditions and the following disclaimer in the documentation
90
+ and/or other materials provided with the distribution.
91
+
92
+ * Neither the name of the copyright holder nor the names of its
93
+ contributors may be used to endorse or promote products derived from
94
+ this software without specific prior written permission.
95
+
96
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
97
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
99
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
100
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
101
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
102
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
103
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
104
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
105
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
106
+
107
+ ```
config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "nomic-uiuc/CodeEmbed",
3
+ "activation_function": "swiglu",
4
+ "architectures": [
5
+ "NomicBertModel"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_hf_nomic_bert.NomicBertConfig",
10
+ "AutoModel": "modeling_hf_nomic_bert.NomicBertModel"
11
+ },
12
+ "bos_token_id": null,
13
+ "causal": false,
14
+ "dense_seq_output": true,
15
+ "embd_pdrop": 0.1,
16
+ "eos_token_id": null,
17
+ "fused_bias_fc": true,
18
+ "fused_dropout_add_ln": true,
19
+ "initializer_range": 0.02,
20
+ "layer_norm_epsilon": 1e-12,
21
+ "max_trained_positions": 2048,
22
+ "mlp_fc1_bias": false,
23
+ "mlp_fc2_bias": false,
24
+ "model_type": "nomic_bert",
25
+ "n_embd": 768,
26
+ "n_head": 12,
27
+ "n_inner": 3072,
28
+ "n_layer": 12,
29
+ "n_positions": 8192,
30
+ "pad_vocab_size_multiple": 64,
31
+ "parallel_block": false,
32
+ "parallel_block_tied_norm": false,
33
+ "prenorm": false,
34
+ "qkv_proj_bias": false,
35
+ "reorder_and_upcast_attn": false,
36
+ "resid_pdrop": 0.1,
37
+ "rotary_emb_base": 1000,
38
+ "rotary_emb_fraction": 1.0,
39
+ "rotary_emb_interleaved": false,
40
+ "rotary_emb_scale_base": null,
41
+ "rotary_scaling_factor": null,
42
+ "scale_attn_by_inverse_layer_idx": false,
43
+ "scale_attn_weights": true,
44
+ "summary_activation": null,
45
+ "summary_first_dropout": 0.1,
46
+ "summary_proj_to_labels": true,
47
+ "summary_type": "cls_index",
48
+ "summary_use_proj": true,
49
+ "torch_dtype": "float32",
50
+ "transformers_version": "4.45.1",
51
+ "type_vocab_size": 2,
52
+ "use_cache": true,
53
+ "use_flash_attn": true,
54
+ "use_rms_norm": false,
55
+ "use_xentropy": true,
56
+ "vocab_size": 30528
57
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "2.7.0.dev0",
4
+ "transformers": "4.39.3",
5
+ "pytorch": "2.1.0+cu121"
6
+ },
7
+ "prompts": {
8
+ "query": "Represent this query for searching relevant code: "
9
+ },
10
+ "default_prompt_name": null
11
+ }
configuration_hf_nomic_bert.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import GPT2Config
2
+
3
+
4
+ class NomicBertConfig(GPT2Config):
5
+ model_type = "nomic_bert"
6
+
7
+ def __init__(
8
+ self,
9
+ prenorm=False,
10
+ parallel_block=False,
11
+ parallel_block_tied_norm=False,
12
+ rotary_emb_fraction=0.0,
13
+ fused_dropout_add_ln=False,
14
+ fused_bias_fc=False,
15
+ use_flash_attn=False,
16
+ use_xentropy=False,
17
+ qkv_proj_bias=True,
18
+ rotary_emb_base=1000,
19
+ rotary_emb_scale_base=None,
20
+ rotary_emb_interleaved=False,
21
+ mlp_fc1_bias=True,
22
+ mlp_fc2_bias=True,
23
+ use_rms_norm=False,
24
+ causal=False,
25
+ type_vocab_size=2,
26
+ dense_seq_output=True,
27
+ pad_vocab_size_multiple=1,
28
+ tie_word_embeddings=True,
29
+ rotary_scaling_factor=1.0,
30
+ max_trained_positions=2048,
31
+ **kwargs,
32
+ ):
33
+ self.prenorm = prenorm
34
+ self.parallel_block = parallel_block
35
+ self.parallel_block_tied_norm = parallel_block_tied_norm
36
+ self.rotary_emb_fraction = rotary_emb_fraction
37
+ self.tie_word_embeddings = tie_word_embeddings
38
+ self.fused_dropout_add_ln = fused_dropout_add_ln
39
+ self.fused_bias_fc = fused_bias_fc
40
+ self.use_flash_attn = use_flash_attn
41
+ self.use_xentropy = use_xentropy
42
+ self.qkv_proj_bias = qkv_proj_bias
43
+ self.rotary_emb_base = rotary_emb_base
44
+ self.rotary_emb_scale_base = rotary_emb_scale_base
45
+ self.rotary_emb_interleaved = rotary_emb_interleaved
46
+ self.mlp_fc1_bias = mlp_fc1_bias
47
+ self.mlp_fc2_bias = mlp_fc2_bias
48
+ self.use_rms_norm = use_rms_norm
49
+ self.causal = causal
50
+ self.type_vocab_size = type_vocab_size
51
+ self.dense_seq_output = dense_seq_output
52
+ self.pad_vocab_size_multiple = pad_vocab_size_multiple
53
+ self.rotary_scaling_factor = rotary_scaling_factor
54
+ self.max_trained_positions = max_trained_positions
55
+
56
+ super().__init__(**kwargs)
failurelens_provenance.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "build_kind": "hf-jobs-stage2-rebuild",
3
+ "job_id": "6ae7d7a8c78863f9c62ff0e8",
4
+ "base_model": "nomic-ai/CodeRankEmbed",
5
+ "base_model_revision": "3c4b60807d71f79b43f3c4363786d9493691f8b1",
6
+ "source_revision": "2985bfcfbf5bf79bc3b3b0589284f6a4ca481970",
7
+ "source_archive_sha256": "c632b33ca539cc6185a4e20bbb68af78cb80a42b3ac9b98c2510efa4316bfc5d",
8
+ "build_script_sha256": "f5554887939ed1b02b7855bad15198f12aceebf58c9c01a987edb2bd6d2138a5",
9
+ "artifact_sha256": "8e8fb971f8c1dce22ae29ea4f682cb8387790ad608e06d3800b62d3413a0a9e4",
10
+ "dataset_sha256": "74909f51b588c311de798bee29b748cfc1ead65fd2948053c8f3a1c729e465c1",
11
+ "training_features_sha256": "baf5af79eb5c8893f84d852232b6540a84348e264f2251b7c4dbb9998f2cb8a9",
12
+ "effective_max_seq_length": 8192,
13
+ "max_observed_training_feature_tokens": 991,
14
+ "training": {
15
+ "git_sha": "2985bfcfbf5bf79bc3b3b0589284f6a4ca481970",
16
+ "config": {
17
+ "seed": 42,
18
+ "epochs": 3,
19
+ "batch_size": 2,
20
+ "learning_rate": 2e-05,
21
+ "weight_decay": 0.01,
22
+ "temperature": 0.07,
23
+ "max_length": 512,
24
+ "optimizer": "adamw",
25
+ "objective": "infonce",
26
+ "model_id": "nomic-ai/CodeRankEmbed",
27
+ "model_revision": "3c4b60807d71f79b43f3c4363786d9493691f8b1",
28
+ "dataset": "failurelens-train-issue17-v2",
29
+ "dataset_sha256": "74909f51b588c311de798bee29b748cfc1ead65fd2948053c8f3a1c729e465c1",
30
+ "split": "repo-level-6-6",
31
+ "train_repo": "pallets/click",
32
+ "val_repo": "python-attrs/attrs",
33
+ "trainable_layers": "last-encoder-layer"
34
+ },
35
+ "history": {
36
+ "train_loss": [
37
+ 0.47753843665122986,
38
+ 0.5231968661149343,
39
+ 0.412482092777888
40
+ ],
41
+ "val_loss": [
42
+ 0.7336968183517456,
43
+ 0.7239548762639364,
44
+ 0.7208325664202372
45
+ ]
46
+ },
47
+ "n_train": 6,
48
+ "n_val": 6,
49
+ "trainable_params": 9440256,
50
+ "total_params": 136731648,
51
+ "artifact_sha256": "8e8fb971f8c1dce22ae29ea4f682cb8387790ad608e06d3800b62d3413a0a9e4",
52
+ "elapsed_seconds": 7.6,
53
+ "peak_gpu_memory_mib": 885,
54
+ "run_metadata": {
55
+ "git_sha": "2985bfcfbf5bf79bc3b3b0589284f6a4ca481970",
56
+ "model_id": "nomic-ai/CodeRankEmbed",
57
+ "model_revision": "3c4b60807d71f79b43f3c4363786d9493691f8b1",
58
+ "dataset_sha256": "74909f51b588c311de798bee29b748cfc1ead65fd2948053c8f3a1c729e465c1",
59
+ "n_train": 6,
60
+ "n_val": 6,
61
+ "trainable_params": 9440256,
62
+ "total_params": 136731648,
63
+ "python": "3.12.3",
64
+ "platform": "Linux-6.12.113-138.209.amzn2023.x86_64-x86_64-with-glibc2.39",
65
+ "torch_version": "2.11.0+cu128",
66
+ "device_name": "Tesla T4",
67
+ "device_memory_mib": 15095
68
+ }
69
+ },
70
+ "dependencies": {
71
+ "torch": "2.11.0+cu128",
72
+ "transformers": "5.22.0",
73
+ "sentence-transformers": "6.2.0",
74
+ "huggingface_hub": "2.4.0",
75
+ "safetensors": "0.8.0",
76
+ "einops": "0.8.1",
77
+ "pydantic": "2.14.2",
78
+ "jsonschema": "4.26.0",
79
+ "typer": "0.27.3"
80
+ },
81
+ "verification": {
82
+ "exact_trained_tensors": true,
83
+ "changed_tensors": 9,
84
+ "changed_layers": [
85
+ 11
86
+ ],
87
+ "offline_cpu_embeddings": true
88
+ },
89
+ "independent_evaluation": "pending; no accuracy or superiority claim",
90
+ "files": {
91
+ "1_Pooling/config.json": "d02ebf56344d20f773449b15d0c10ee9a86a9178f3b3c9bfecb8b87d4350ce38",
92
+ "config.json": "5ff856a41d0f53ef2d74520627d464bd75c2efd8f26f381bd528654895c29b6c",
93
+ "config_sentence_transformers.json": "06bc4c2dc7098e98669beb67cf21dc1373e44a77c7eecdf70aad6585d87190cf",
94
+ "configuration_hf_nomic_bert.py": "8632792e922e62ab1a6feaab15baf406e223c0547a21de23ab4f520b2b36d674",
95
+ "model.safetensors": "8e8fb971f8c1dce22ae29ea4f682cb8387790ad608e06d3800b62d3413a0a9e4",
96
+ "modeling_hf_nomic_bert.py": "f49c7bb2f834ad9915f98326759a712a7804faa870c038c31ac04cba7a2f77a5",
97
+ "modules.json": "8f4b264b80206c830bebbdcae377e137925650a433b689343a63bdc9b3145460",
98
+ "sentence_bert_config.json": "d8ecbf1eb946d17aec64c83e6614e5ec1b19b62498cf72a4ed4ec882c86af07e",
99
+ "special_tokens_map.json": "5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a",
100
+ "tokenizer.json": "91f1def9b9391fdabe028cd3f3fcc4efd34e5d1f08c3bf2de513ebb5911a1854",
101
+ "tokenizer_config.json": "7809f768ee3614618b3f1b91dcbfab4f6a9d4b79fb1ad5d17feb65a7c1bb5b7a",
102
+ "vocab.txt": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
103
+ }
104
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e8fb971f8c1dce22ae29ea4f682cb8387790ad608e06d3800b62d3413a0a9e4
3
+ size 546938144
modeling_hf_nomic_bert.py ADDED
@@ -0,0 +1,1225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # This BERT implementation is based on our MLPerf 2.0 and MLPerf 2.1 BERT implementation.
3
+ # https://github.com/mlcommons/training_results_v2.0/blob/main/HazyResearch/benchmarks/bert/implementations/pytorch/modeling.py
4
+ # https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py
5
+
6
+ import logging
7
+
8
+ # Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py
9
+ import os
10
+ import re
11
+ from collections import OrderedDict
12
+ from functools import partial
13
+ from typing import List, Optional, Tuple, Union
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from einops import rearrange, repeat
19
+ from safetensors.torch import load_file as safe_load_file
20
+ from transformers import GPT2Config, PreTrainedModel
21
+ from transformers.models.bert.modeling_bert import (
22
+ BaseModelOutputWithPoolingAndCrossAttentions,
23
+ MaskedLMOutput,
24
+ SequenceClassifierOutput,
25
+ )
26
+ from transformers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME
27
+ from transformers.utils.hub import cached_file, get_checkpoint_shard_files
28
+
29
+ from .configuration_hf_nomic_bert import NomicBertConfig
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ # adapted from flash attention, added safe serialization option for hf models
35
+ def state_dict_from_pretrained(model_name, safe_serialization=False, device=None, dtype=None):
36
+ # If not fp32, then we don't want to load directly to the GPU
37
+ mapped_device = "cpu" if dtype not in [torch.float32, None] else device
38
+ is_sharded = False
39
+ load_safe = False
40
+ resolved_archive_file = None
41
+
42
+ weights_path = os.path.join(model_name, WEIGHTS_NAME)
43
+ weights_index_path = os.path.join(model_name, WEIGHTS_INDEX_NAME)
44
+ safe_weights_path = os.path.join(model_name, SAFE_WEIGHTS_NAME)
45
+ safe_weights_index_path = os.path.join(model_name, SAFE_WEIGHTS_INDEX_NAME)
46
+
47
+ if os.path.isfile(weights_path):
48
+ resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
49
+ elif os.path.isfile(weights_index_path):
50
+ resolved_archive_file = cached_file(model_name, WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False)
51
+ is_sharded = True
52
+ elif os.path.isfile(safe_weights_path):
53
+ resolved_archive_file = cached_file(model_name, SAFE_WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
54
+ load_safe = True
55
+ elif os.path.isfile(safe_weights_index_path):
56
+ resolved_archive_file = cached_file(
57
+ model_name, SAFE_WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False
58
+ )
59
+ is_sharded = True
60
+ load_safe = True
61
+ else: # Try loading from HF hub instead of from local files
62
+ weight_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
63
+ resolved_archive_file = cached_file(model_name, weight_name, _raise_exceptions_for_missing_entries=False)
64
+ if resolved_archive_file is None:
65
+ weight_index = WEIGHTS_INDEX_NAME if not safe_serialization else SAFE_WEIGHTS_INDEX_NAME
66
+ resolved_archive_file = cached_file(model_name, weight_index, _raise_exceptions_for_missing_entries=False)
67
+ if resolved_archive_file is not None:
68
+ is_sharded = True
69
+
70
+ load_safe = safe_serialization
71
+
72
+ if resolved_archive_file is None:
73
+ raise EnvironmentError(f"Model name {model_name} was not found.")
74
+
75
+ if load_safe:
76
+ loader = partial(safe_load_file, device=mapped_device)
77
+ else:
78
+ loader = partial(torch.load, map_location=mapped_device)
79
+
80
+ if is_sharded:
81
+ # resolved_archive_file becomes a list of files that point to the different
82
+ # checkpoint shards in this case.
83
+ resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(model_name, resolved_archive_file)
84
+ state_dict = {}
85
+ for sharded_file in resolved_archive_file:
86
+ state_dict.update(loader(sharded_file))
87
+ else:
88
+ state_dict = loader(resolved_archive_file)
89
+ # Convert dtype before moving to GPU to save memory
90
+ if dtype is not None:
91
+ state_dict = {k: v.to(dtype=dtype) for k, v in state_dict.items()}
92
+ state_dict = {k: v.to(device=device) for k, v in state_dict.items()}
93
+ return state_dict
94
+
95
+
96
+ def filter_shapes(state_dict, model):
97
+ """
98
+ Filters the state dict to match the current model shape.
99
+ """
100
+ filtered_state_dict = {}
101
+ for key, value in state_dict.items():
102
+ if key in model.state_dict():
103
+ if value.shape == model.state_dict()[key].shape:
104
+ filtered_state_dict[key] = value
105
+ return filtered_state_dict
106
+
107
+
108
+ def remap_bert_state_dict(state_dict, config, remove_bert=False, remove_cls_weights=False, add_pooling_layer=False):
109
+ """
110
+ Map the state_dict of a Huggingface BERT model to be flash_attn compatible.
111
+ """
112
+
113
+ def add_bert_prefix(key):
114
+ # prepend bert. to the key
115
+ if key.startswith("bert.") or key.startswith("cls."):
116
+ return key
117
+ return f"bert.{key}"
118
+
119
+ state_dict = OrderedDict((add_bert_prefix(k), v) for k, v in state_dict.items())
120
+
121
+ # LayerNorm
122
+ def key_mapping_ln_gamma_beta(key):
123
+ key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key)
124
+ key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key)
125
+ return key
126
+
127
+ state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items())
128
+
129
+ # Layers
130
+ def key_mapping_layers(key):
131
+ return re.sub(r"^bert.encoder.layer\.", "bert.encoder.layers.", key)
132
+
133
+ state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items())
134
+
135
+ # LayerNorm
136
+ def key_mapping_ln(key):
137
+ key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key)
138
+ key = re.sub(
139
+ r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)",
140
+ r"bert.encoder.layers.\1.norm1.\2",
141
+ key,
142
+ )
143
+ key = re.sub(
144
+ r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)",
145
+ r"bert.encoder.layers.\1.norm2.\2",
146
+ key,
147
+ )
148
+ key = re.sub(
149
+ r"^cls.predictions.transform.LayerNorm.(weight|bias)",
150
+ r"cls.predictions.transform.layer_norm.\1",
151
+ key,
152
+ )
153
+ return key
154
+
155
+ state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())
156
+
157
+ # MLP
158
+ def key_mapping_mlp(key):
159
+ key = re.sub(
160
+ r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)",
161
+ r"bert.encoder.layers.\1.mlp.fc1.\2",
162
+ key,
163
+ )
164
+ key = re.sub(
165
+ r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)",
166
+ r"bert.encoder.layers.\1.mlp.fc2.\2",
167
+ key,
168
+ )
169
+ return key
170
+
171
+ state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())
172
+
173
+ # Attention
174
+ last_layer_subset = getattr(config, "last_layer_subset", False)
175
+ for d in range(config.num_hidden_layers):
176
+ if f"bert.encoder.layers.{d}.attention.self.query.weight" not in state_dict:
177
+ continue
178
+ Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight")
179
+ Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight")
180
+ Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight")
181
+ bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias")
182
+ bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias")
183
+ bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias")
184
+ if not (last_layer_subset and d == config.num_hidden_layers - 1):
185
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0)
186
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0)
187
+ else:
188
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.weight"] = Wq
189
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.weight"] = torch.cat([Wk, Wv], dim=0)
190
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.bias"] = bq
191
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.bias"] = torch.cat([bk, bv], dim=0)
192
+
193
+ def key_mapping_attn(key):
194
+ return re.sub(
195
+ r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)",
196
+ r"bert.encoder.layers.\1.attn.out_proj.\2",
197
+ key,
198
+ )
199
+
200
+ state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
201
+
202
+ def key_mapping_decoder_bias(key):
203
+ return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key)
204
+
205
+ # remove nsp weights, we don't use
206
+ state_dict.pop("cls.seq_relationship.weight", None)
207
+ state_dict.pop("cls.seq_relationship.bias", None)
208
+ state_dict.pop("bert.embeddings.position_ids", None)
209
+
210
+ state_dict = OrderedDict((key_mapping_decoder_bias(k), v) for k, v in state_dict.items())
211
+
212
+ if remove_cls_weights:
213
+ cls_weights = [
214
+ "cls.predictions.decoder.bias",
215
+ "cls.predictions.transform.dense.weight",
216
+ "cls.predictions.transform.dense.bias",
217
+ "cls.predictions.transform.layer_norm.weight",
218
+ "cls.predictions.transform.layer_norm.bias",
219
+ "cls.predictions.decoder.weight",
220
+ ]
221
+ for weight in cls_weights:
222
+ state_dict.pop(weight, None)
223
+
224
+ # Word embedding
225
+ pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
226
+ if pad_vocab_size_multiple > 1:
227
+ word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"]
228
+ state_dict["bert.embeddings.word_embeddings.weight"] = F.pad(
229
+ word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0])
230
+ )
231
+ if not remove_cls_weights:
232
+ decoder_weight = state_dict["cls.predictions.decoder.weight"]
233
+ state_dict["cls.predictions.decoder.weight"] = F.pad(
234
+ decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0])
235
+ )
236
+ # If the vocab was padded, we want to set the decoder bias for those padded indices to be
237
+ # strongly negative (i.e. the decoder shouldn't predict those indices).
238
+ # TD [2022-05-09]: I don't think it affects the MLPerf training.
239
+ if "cls.predictions.decoder.bias" in state_dict:
240
+ decoder_bias = state_dict["cls.predictions.decoder.bias"]
241
+ state_dict["cls.predictions.decoder.bias"] = F.pad(
242
+ decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0
243
+ )
244
+
245
+ if add_pooling_layer is False:
246
+ pooler_weights = [
247
+ "bert.pooler.dense.weight",
248
+ "bert.pooler.dense.bias",
249
+ ]
250
+ for key in pooler_weights:
251
+ state_dict.pop(key, None)
252
+
253
+ if remove_bert:
254
+
255
+ def remove_bert_prefix(key):
256
+ key = re.sub(r"^bert.", "", key)
257
+ return key
258
+
259
+ state_dict = OrderedDict((remove_bert_prefix(k), v) for k, v in state_dict.items())
260
+
261
+ return state_dict
262
+
263
+
264
+ class NomicBertPreTrainedModel(PreTrainedModel):
265
+ """An abstract class to handle weights initialization and
266
+ a simple interface for dowloading and loading pretrained models.
267
+ """
268
+
269
+ config_class = NomicBertConfig
270
+ base_model_prefix = "model"
271
+ supports_gradient_checkpointing = True
272
+ _no_split_modules = ["Block"]
273
+ _skip_keys_device_placement = "past_key_values"
274
+
275
+ def __init__(self, config, *inputs, **kwargs):
276
+ super().__init__(config)
277
+ if not isinstance(config, GPT2Config):
278
+ raise ValueError(
279
+ "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. "
280
+ "To create a model from a Google pretrained model use "
281
+ "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
282
+ self.__class__.__name__, self.__class__.__name__
283
+ )
284
+ )
285
+ self.config = config
286
+
287
+ @classmethod
288
+ def from_pretrained(cls, model_name, config=None, *inputs, **kwargs):
289
+ """
290
+ Instantiate a NomicBertPreTrainedModel from a pre-trained model file or a pytorch state dict.
291
+ Download and cache the pre-trained model file if needed.
292
+ Params:
293
+ pretrained_model_name_or_path: either:
294
+ - a path or url to a pretrained model archive containing:
295
+ . `bert_config.json` a configuration file for the model
296
+ . `pytorch_model.bin` a PyTorch dump of a NomicBertForPretraining instance
297
+ - a path or url to a pretrained model archive containing:
298
+ . `bert_config.json` a configuration file for the model
299
+ . `model.chkpt` a TensorFlow checkpoint
300
+ *inputs, **kwargs: additional input for the specific NomicBert class
301
+ (ex: num_labels for NomicBertForSequenceClassification)
302
+ """
303
+ # Instantiate model.
304
+ if config is None:
305
+ config = cls.config_class.from_pretrained(model_name)
306
+ remove_cls = cls != NomicBertForPreTraining
307
+ remove_bert_prefix = cls != NomicBertForPreTraining
308
+ ignore_mismatched_shapes = kwargs.pop("ignore_mismatched_sizes", False)
309
+ num_labels = kwargs.pop("num_labels", None)
310
+ rotary_scaling_factor = kwargs.pop("rotary_scaling_factor", None)
311
+ if rotary_scaling_factor:
312
+ config.rotary_scaling_factor = rotary_scaling_factor
313
+
314
+ if config.n_positions <= 0 and config.rotary_emb_fraction > 0:
315
+ config.n_positions = 2048
316
+ if num_labels:
317
+ config.num_labels = num_labels
318
+
319
+ if "add_pooling_layer" in kwargs:
320
+ model = cls(config, *inputs, add_pooling_layer=kwargs.pop("add_pooling_layer"))
321
+ else:
322
+ if cls == NomicBertModel:
323
+ model = cls(config, *inputs, add_pooling_layer=False)
324
+ else:
325
+ model = cls(config, *inputs)
326
+ # TODO: fix this
327
+ # Assuming we know what we're doing when loading from disk
328
+ # Prob a bad assumption but i'm tired and want to train this asap
329
+ if os.path.exists(model_name):
330
+ model_path = f"{model_name}/pytorch_model.bin"
331
+ if os.path.exists(model_path):
332
+ state_dict = torch.load(f"{model_name}/pytorch_model.bin")
333
+ else:
334
+ model_path = f"{model_name}/model.safetensors"
335
+ if not os.path.exists(model_path):
336
+ raise ValueError(f"Model path {model_path} not found")
337
+ state_dict = safe_load_file(model_path)
338
+
339
+ if ignore_mismatched_shapes:
340
+ state_dict = filter_shapes(state_dict, model)
341
+ load_return = model.load_state_dict(state_dict, strict=False)
342
+ else:
343
+ # TODO: can probably check config class and see if we need to remap from a bert model
344
+ state_dict = state_dict_from_pretrained(model_name, safe_serialization=kwargs.get("safe_serialization", False))
345
+ state_dict = remap_bert_state_dict(
346
+ state_dict,
347
+ config,
348
+ remove_bert=remove_bert_prefix,
349
+ remove_cls_weights=remove_cls,
350
+ add_pooling_layer=getattr(config, "add_pooling_layer", False),
351
+ )
352
+ if ignore_mismatched_shapes:
353
+ state_dict = filter_shapes(state_dict, model)
354
+
355
+ load_return = model.load_state_dict(state_dict, strict=True)
356
+ logger.warning(load_return)
357
+ return model
358
+
359
+ def _set_gradient_checkpointing(self, module, value=False):
360
+ if isinstance(module, NomicBertEncoder):
361
+ module.gradient_checkpointing = value
362
+
363
+
364
+ # https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748
365
+ def _init_weights(module, initializer_range=0.02):
366
+ if isinstance(module, nn.Linear):
367
+ nn.init.normal_(module.weight, std=initializer_range)
368
+ if module.bias is not None:
369
+ nn.init.zeros_(module.bias)
370
+ elif isinstance(module, nn.Embedding):
371
+ nn.init.normal_(module.weight, std=initializer_range)
372
+ if module.padding_idx is not None:
373
+ nn.init.zeros_(module.weight[module.padding_idx])
374
+
375
+
376
+ class NomicBertEmbeddings(nn.Module):
377
+ def __init__(self, config):
378
+ """
379
+ If max_position_embeddings <= 0, there's no position embeddings
380
+ If type_vocab_size <= 0, there's no token type embeddings
381
+ """
382
+ super().__init__()
383
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
384
+ self.max_position_embeddings = config.max_position_embeddings if config.rotary_emb_fraction <= 0 else 0
385
+ self.type_vocab_size = config.type_vocab_size
386
+ if self.max_position_embeddings > 0 and config.rotary_emb_fraction <= 0:
387
+ self.position_embeddings = nn.Embedding(
388
+ config.max_position_embeddings,
389
+ config.hidden_size,
390
+ )
391
+ if self.type_vocab_size > 0:
392
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
393
+
394
+ def forward(self, input_ids, position_ids=None, token_type_ids=None):
395
+ """
396
+ input_ids: (batch, seqlen)
397
+ position_ids: (batch, seqlen)
398
+ token_type_ids: (batch, seqlen)
399
+ """
400
+ batch_size, seqlen = input_ids.shape
401
+ embeddings = self.word_embeddings(input_ids)
402
+
403
+ if self.type_vocab_size > 0:
404
+ if token_type_ids is None:
405
+ token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device)
406
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
407
+ embeddings = embeddings + token_type_embeddings
408
+
409
+ if self.max_position_embeddings > 0:
410
+ if position_ids is None:
411
+ position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device)
412
+ position_embeddings = self.position_embeddings(position_ids)
413
+ embeddings = embeddings + position_embeddings
414
+ return embeddings
415
+
416
+
417
+ class NomicBertMLP(nn.Module):
418
+ def __init__(
419
+ self,
420
+ in_features,
421
+ hidden_features=None,
422
+ out_features=None,
423
+ activation=F.gelu,
424
+ bias1=True,
425
+ bias2=True,
426
+ return_residual=False,
427
+ fused_bias_fc=False,
428
+ ):
429
+ super().__init__()
430
+ out_features = out_features if out_features is not None else in_features
431
+ hidden_features = hidden_features if hidden_features is not None else in_features * 4
432
+ self.return_residual = return_residual
433
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1)
434
+ approximate = "tanh" if activation in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
435
+ self.activation = nn.GELU(approximate=approximate) if activation == "gelu" else activation
436
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
437
+
438
+ def forward(self, x):
439
+ y = self.fc1(x)
440
+ y = self.activation(y)
441
+ y = self.fc2(y)
442
+ return y if not self.return_residual else (y, x)
443
+
444
+
445
+ class NomciBertGatedMLP(nn.Module):
446
+ def __init__(
447
+ self,
448
+ in_features,
449
+ hidden_features=None,
450
+ out_features=None,
451
+ activation=F.sigmoid,
452
+ bias1=True,
453
+ bias2=True,
454
+ multiple_of=256,
455
+ return_residual=False,
456
+ fused_bias_fc=True,
457
+ device=None,
458
+ dtype=None,
459
+ ):
460
+ super().__init__()
461
+ out_features = out_features if out_features is not None else in_features
462
+ hidden_features = hidden_features if hidden_features is not None else int(8 * in_features / 3)
463
+ hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of
464
+ self.return_residual = return_residual
465
+
466
+ self.fc11 = nn.Linear(in_features, hidden_features, bias=bias1)
467
+ self.fc12 = nn.Linear(in_features, hidden_features, bias=bias1)
468
+ self.activation = activation
469
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
470
+
471
+ def forward(self, x):
472
+ y = self.fc11(x)
473
+ gate = self.fc12(x)
474
+ if self.activation == F.sigmoid: # Special case for GLU
475
+ y = F.glu(torch.cat([y, gate], dim=-1), dim=-1)
476
+ else:
477
+ y = y * self.activation(gate)
478
+ y = self.fc2(y)
479
+ return y if not self.return_residual else (y, x)
480
+
481
+
482
+ def rotate_half(x, interleaved=False):
483
+ if not interleaved:
484
+ x1, x2 = x.chunk(2, dim=-1)
485
+ return torch.cat((-x2, x1), dim=-1)
486
+ else:
487
+ x1, x2 = x[..., ::2], x[..., 1::2]
488
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
489
+
490
+
491
+ def apply_rotary_emb(x, cos, sin, offset=0, interleaved=False):
492
+ """
493
+ x: (batch_size, seqlen, nheads, headdim)
494
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
495
+ """
496
+ ro_dim = cos.shape[-1] * 2
497
+ assert ro_dim <= x.shape[-1]
498
+ cos, sin = (
499
+ cos[offset : offset + x.shape[1]],
500
+ sin[offset : offset + x.shape[1]],
501
+ )
502
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
503
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
504
+ return torch.cat(
505
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
506
+ dim=-1,
507
+ )
508
+
509
+
510
+ class NomicBertRotaryEmbedding(nn.Module):
511
+ def __init__(
512
+ self,
513
+ dim: int,
514
+ base=10000.0,
515
+ interleaved=False,
516
+ scale_base=None,
517
+ pos_idx_in_fp32=True,
518
+ device=None,
519
+ ):
520
+ """
521
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
522
+ of 1st half and 2nd half (GPT-NeoX style).
523
+ pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32,
524
+ otherwise they might be in lower precision.
525
+ This option was added because previously (before 2023-07-02), when we construct
526
+ the position indices, we use the dtype of self.inv_freq. In most cases this would
527
+ be fp32, but if the model is trained in pure bf16 (not mixed precision), then
528
+ self.inv_freq would be bf16, and the position indices are also in bf16.
529
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
530
+ embeddings for some positions will coincide.
531
+ To maintain compatibility with models previously trained in pure bf16,
532
+ we add this option.
533
+ """
534
+ super().__init__()
535
+ self.dim = dim
536
+ self.base = float(base)
537
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
538
+ # Generate and save the inverse frequency buffer (non trainable)
539
+ inv_freq = self._compute_inv_freq(device)
540
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
541
+ self.interleaved = interleaved
542
+ self.scale_base = scale_base
543
+ scale = (
544
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
545
+ if scale_base is not None
546
+ else None
547
+ )
548
+ self.register_buffer("scale", scale, persistent=False)
549
+
550
+ self._seq_len_cached = 0
551
+ self._cos_cached = None
552
+ self._sin_cached = None
553
+ self._cos_k_cached = None
554
+ self._sin_k_cached = None
555
+
556
+ def _compute_inv_freq(self, device=None):
557
+ return 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
558
+
559
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
560
+ # Reset the tables if the sequence length has changed,
561
+ # if we're on a new device (possibly due to tracing for instance),
562
+ # or if we're switching from inference mode to training
563
+ if (
564
+ seqlen > self._seq_len_cached
565
+ or self._cos_cached is None
566
+ or self._cos_cached.device != device
567
+ or self._cos_cached.dtype != dtype
568
+ or (self.training and self._cos_cached.is_inference())
569
+ ):
570
+ self._seq_len_cached = seqlen
571
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
572
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
573
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
574
+ if self.pos_idx_in_fp32:
575
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
576
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
577
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
578
+ # cos & sin output to change significantly.
579
+ # We want to recompute self.inv_freq if it was not loaded in fp32
580
+ if self.inv_freq.dtype != torch.float32:
581
+ inv_freq = self._compute_inv_freq(device=device)
582
+ else:
583
+ inv_freq = self.inv_freq
584
+ else:
585
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
586
+ inv_freq = self.inv_freq
587
+ # Don't do einsum, it converts fp32 to fp16 under AMP
588
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
589
+ freqs = torch.outer(t, inv_freq)
590
+ self._cos_cached = torch.cos(freqs).to(dtype)
591
+ self._sin_cached = torch.sin(freqs).to(dtype)
592
+
593
+ def forward(
594
+ self,
595
+ qkv: torch.Tensor,
596
+ kv: Optional[torch.Tensor] = None,
597
+ seqlen_offset: Union[int, torch.Tensor] = 0,
598
+ max_seqlen: Optional[int] = None,
599
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
600
+ """
601
+ qkv: (batch, seqlen, 3, nheads, headdim) if kv is none,
602
+ else it's just q of shape (batch, seqlen, nheads, headdim)
603
+ kv: (batch, seqlen, 2, nheads, headdim)
604
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
605
+ Most commonly used in inference when we have KV cache.
606
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
607
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
608
+ Apply rotary embedding *inplace* to qkv and / or kv.
609
+ """
610
+ seqlen = qkv.shape[1]
611
+ if seqlen > self._seq_len_cached:
612
+ self._update_cos_sin_cache(seqlen, device=qkv.device, dtype=qkv.dtype)
613
+ elif max_seqlen is not None:
614
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
615
+ elif isinstance(seqlen_offset, int):
616
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
617
+
618
+ q_rot = apply_rotary_emb(qkv[:, :, 0], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
619
+ k_rot = apply_rotary_emb(qkv[:, :, 1], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
620
+ return torch.stack((q_rot, k_rot, qkv[:, :, 2]), dim=2)
621
+
622
+
623
+ class NomicBertDynamicNTKRotaryEmbedding(NomicBertRotaryEmbedding):
624
+ def __init__(self, rotary_scaling_factor, max_position_embeddings, **kwargs):
625
+ super().__init__(**kwargs)
626
+ self.rotary_scaling_factor = rotary_scaling_factor
627
+ self.max_position_embeddings = max_position_embeddings
628
+
629
+ def _compute_inv_freq(self, base=None, device=None):
630
+ if base is None:
631
+ base = self.base
632
+ return 1.0 / (base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
633
+
634
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
635
+ # Reset the tables if the sequence length has changed,
636
+ # if we're on a new device (possibly due to tracing for instance),
637
+ # or if we're switching from inference mode to training
638
+ if seqlen > self.max_position_embeddings:
639
+ base = self.base * (
640
+ (self.rotary_scaling_factor * seqlen / self.max_position_embeddings) - (self.rotary_scaling_factor - 1)
641
+ ) ** (self.dim / (self.dim - 2))
642
+ inv_freq = self._compute_inv_freq(base=base, device=device)
643
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
644
+
645
+ if (
646
+ seqlen > self._seq_len_cached
647
+ or self._cos_cached is None
648
+ or self._cos_cached.device != device
649
+ or self._cos_cached.dtype != dtype
650
+ or (self.training and self._cos_cached.is_inference())
651
+ ):
652
+ self._seq_len_cached = seqlen
653
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
654
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
655
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
656
+ if self.pos_idx_in_fp32:
657
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
658
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
659
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
660
+ # cos & sin output to change significantly.
661
+ # We want to recompute self.inv_freq if it was not loaded in fp32
662
+ if self.inv_freq.dtype != torch.float32:
663
+ if seqlen > self.max_position_embeddings:
664
+ base = self.base * (
665
+ (self.scaling_factor * seqlen / self.max_position_embeddings) - (self.scaling_factor - 1)
666
+ ) ** (self.dim / (self.dim - 2))
667
+ else:
668
+ base = self.base
669
+ inv_freq = self._compute_inv_freq(device=device, base=base)
670
+ else:
671
+ inv_freq = self.inv_freq
672
+ else:
673
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
674
+ inv_freq = self.inv_freq
675
+ # Don't do einsum, it converts fp32 to fp16 under AMP
676
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
677
+ freqs = torch.outer(t, inv_freq)
678
+ if self.scale is None:
679
+ self._cos_cached = torch.cos(freqs).to(dtype)
680
+ self._sin_cached = torch.sin(freqs).to(dtype)
681
+ else:
682
+ power = (
683
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
684
+ ) / self.scale_base
685
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
686
+ # We want the multiplication by scale to happen in fp32
687
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
688
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
689
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
690
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
691
+
692
+
693
+ class NomicBertAttention(nn.Module):
694
+ """Multi-head self-attention and cross-attention"""
695
+
696
+ def __init__(
697
+ self,
698
+ config,
699
+ ) -> None:
700
+ """
701
+ num_heads_kv: can be used to toggle MQA / GQA. If None, use num_heads.
702
+ return_residual: whether to return the input x along with the output. This is for
703
+ performance reason: for post-norm architecture, returning the input allows us
704
+ to fuse the backward of nn.Linear with the residual connection.
705
+ """
706
+ super().__init__()
707
+ self.embed_dim = config.n_embd
708
+ self.use_flash_attn = config.use_flash_attn
709
+ self.fused_bias_fc = config.fused_bias_fc
710
+
711
+ self.num_heads = config.n_head
712
+ self.num_heads_kv = config.num_heads_kv if getattr(config, "num_heads_kv", None) is not None else self.num_heads
713
+ assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads"
714
+ self.head_dim = self.embed_dim // self.num_heads
715
+ # we don't really support mqa / gqa for now
716
+ qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv)
717
+
718
+ self.register_buffer(
719
+ "norm_factor",
720
+ torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype()),
721
+ persistent=False,
722
+ )
723
+
724
+ self.rotary_emb_dim = self.head_dim * config.rotary_emb_fraction
725
+ if self.rotary_emb_dim > 0:
726
+ if config.rotary_scaling_factor:
727
+ self.rotary_emb = NomicBertDynamicNTKRotaryEmbedding(
728
+ dim=self.rotary_emb_dim,
729
+ base=config.rotary_emb_base,
730
+ scale_base=config.rotary_emb_scale_base,
731
+ interleaved=config.rotary_emb_interleaved,
732
+ rotary_scaling_factor=config.rotary_scaling_factor,
733
+ max_position_embeddings=config.max_trained_positions,
734
+ )
735
+ else:
736
+ self.rotary_emb = NomicBertRotaryEmbedding(
737
+ dim=self.rotary_emb_dim,
738
+ base=config.rotary_emb_base,
739
+ scale_base=config.rotary_emb_scale_base,
740
+ interleaved=config.rotary_emb_interleaved,
741
+ )
742
+ # bug in xformers: https://github.com/facebookresearch/xformers/issues/841
743
+ # uses the head dimension instead of the sequence dimension
744
+ self.rotary_head_dim = getattr(config, "rotary_head_dim", False)
745
+
746
+ self.Wqkv = nn.Linear(self.embed_dim, qkv_dim, bias=config.qkv_proj_bias)
747
+
748
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_proj_bias)
749
+ self.causal = config.causal
750
+ self.drop = nn.Dropout(config.attn_pdrop)
751
+
752
+ def forward(
753
+ self,
754
+ hidden_states: torch.Tensor,
755
+ attention_mask: Optional[torch.Tensor] = None,
756
+ position_ids: Optional[torch.LongTensor] = None,
757
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
758
+ output_attentions: bool = False,
759
+ use_cache: bool = False,
760
+ is_padded_inputs: Optional[bool] = True,
761
+ cu_seqlens: Optional[torch.Tensor] = None,
762
+ max_seq_len: Optional[int] = None,
763
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
764
+
765
+ has_layer_past = past_key_value is not None
766
+
767
+ if has_layer_past:
768
+ past_key_value = past_key_value[0]
769
+ past_len = past_key_value[1]
770
+ else:
771
+ past_len = 0
772
+
773
+ qkv = self.Wqkv(hidden_states)
774
+ qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
775
+
776
+ past_key_value = (past_key_value, past_len + qkv.size(1)) if use_cache else None
777
+
778
+ if self.rotary_emb_dim > 0:
779
+ if self.rotary_head_dim:
780
+ qkv = rearrange(qkv, "b s three h d -> b h three s d")
781
+ qkv = self.rotary_emb(qkv, seqlen_offset=past_len)
782
+
783
+ if self.rotary_head_dim:
784
+ qkv = rearrange(qkv, "b h three s d -> b s three h d")
785
+
786
+ query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
787
+
788
+ query = query.permute(0, 2, 1, 3)
789
+ key = key.permute(0, 2, 1, 3)
790
+ value = value.permute(0, 2, 1, 3)
791
+
792
+ attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
793
+ if attention_mask is not None:
794
+ attention_scores = attention_scores + attention_mask
795
+
796
+ attentions_probs = F.softmax(attention_scores, dim=-1)
797
+ attentions_probs = self.drop(attentions_probs)
798
+
799
+ attn_output = torch.matmul(attentions_probs, value)
800
+ attn_output = rearrange(attn_output.permute(0, 2, 1, 3), "... h d -> ... (h d)")
801
+
802
+ attn_output = self.out_proj(attn_output)
803
+
804
+ return attn_output
805
+
806
+
807
+ class NomicBertBlock(nn.Module):
808
+ def __init__(
809
+ self,
810
+ config,
811
+ ):
812
+ super().__init__()
813
+ self.prenorm = config.prenorm
814
+ self.fused_dropout_add_ln = config.fused_dropout_add_ln
815
+
816
+ self.attn = NomicBertAttention(config)
817
+ activation = (
818
+ F.sigmoid
819
+ if config.activation_function == "glu"
820
+ else (F.silu if config.activation_function == "swiglu" else F.gelu)
821
+ )
822
+ if config.activation_function in ["glu", "swiglu", "geglu"]:
823
+ self.mlp = NomciBertGatedMLP(
824
+ config.n_embd,
825
+ hidden_features=config.n_inner,
826
+ bias1=config.mlp_fc1_bias,
827
+ bias2=config.mlp_fc2_bias,
828
+ activation=activation,
829
+ fused_bias_fc=config.fused_bias_fc,
830
+ )
831
+ else:
832
+ self.mlp = NomicBertMLP(
833
+ config.n_embd,
834
+ hidden_features=config.n_inner,
835
+ bias1=config.mlp_fc1_bias,
836
+ bias2=config.mlp_fc2_bias,
837
+ activation=activation,
838
+ fused_bias_fc=config.fused_bias_fc,
839
+ )
840
+
841
+ self.dropout1 = nn.Dropout(config.resid_pdrop)
842
+ self.norm1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
843
+ self.norm2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
844
+ self.dropout2 = nn.Dropout(config.resid_pdrop)
845
+
846
+ def forward(
847
+ self,
848
+ hidden_states: torch.Tensor,
849
+ hidden_states2: torch.Tensor,
850
+ residual: Optional[torch.Tensor] = None,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
854
+ is_padded_inputs: Optional[bool] = True,
855
+ output_attentions: Optional[bool] = False,
856
+ use_cache: Optional[bool] = False,
857
+ cu_seqlens: Optional[torch.Tensor] = None,
858
+ max_seq_len: Optional[int] = None,
859
+ ):
860
+ r"""Pass the input through the encoder layer.
861
+ Args:
862
+ hidden_states: the sequence to the encoder layer (required).
863
+ residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual))
864
+ mixer_subset: for cross-attention only. If not None, will take a subset of x
865
+ before applying the query projection. Useful for e.g., ViT where we only care
866
+ about the CLS token in the last layer.
867
+ """
868
+ if self.prenorm:
869
+ dropped = self.dropout1(hidden_states)
870
+ residual = (dropped + residual) if residual is not None else dropped
871
+ hidden_states = self.norm1(residual.to(dtype=self.norm1.weight.dtype))
872
+ hidden_states = self.attn(
873
+ hidden_states,
874
+ attention_mask=attention_mask,
875
+ is_padded_inputs=is_padded_inputs,
876
+ cu_seqlens=cu_seqlens,
877
+ max_seq_len=max_seq_len,
878
+ )
879
+
880
+ dropped = self.dropout2(hidden_states)
881
+ residual = (dropped + residual) if residual is not None else dropped
882
+ hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype))
883
+ hidden_states = self.mlp(hidden_states)
884
+
885
+ return hidden_states, None, residual
886
+ else:
887
+ assert residual is None
888
+ attn_outputs = self.attn(
889
+ hidden_states,
890
+ attention_mask=attention_mask,
891
+ is_padded_inputs=is_padded_inputs,
892
+ cu_seqlens=cu_seqlens,
893
+ max_seq_len=max_seq_len,
894
+ )
895
+ hidden_states = self.norm1((self.dropout1(attn_outputs) + hidden_states).to(dtype=self.norm1.weight.dtype))
896
+ mlp_out = self.mlp(hidden_states)
897
+
898
+ hidden_states = self.norm2((self.dropout2(mlp_out) + hidden_states).to(dtype=self.norm2.weight.dtype))
899
+ return hidden_states, None, None
900
+
901
+
902
+ class NomicBertEncoder(nn.Module):
903
+ def __init__(self, config: GPT2Config):
904
+ super().__init__()
905
+ self.layers = nn.ModuleList([NomicBertBlock(config) for _ in range(config.n_layer)])
906
+ self.gradient_checkpointing = False
907
+ self.config = config
908
+
909
+ def forward(
910
+ self,
911
+ hidden_states: torch.LongTensor = None,
912
+ attention_mask: Optional[torch.Tensor] = None,
913
+ position_ids: Optional[torch.LongTensor] = None,
914
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
915
+ inputs_embeds: Optional[torch.FloatTensor] = None,
916
+ use_cache: Optional[bool] = None,
917
+ output_attentions: Optional[bool] = None,
918
+ output_hidden_states: Optional[bool] = None,
919
+ return_dict: Optional[bool] = None,
920
+ is_padded_inputs: Optional[bool] = True,
921
+ ):
922
+ """If subset_mask is not None, we only want output for the subset of the sequence.
923
+ This means that we only compute the last layer output for these tokens.
924
+ subset_mask: (batch, seqlen), dtype=torch.bool
925
+ """
926
+ hidden_states2 = None
927
+ residual = None
928
+
929
+ for _, layer in enumerate(self.layers):
930
+ if self.gradient_checkpointing and self.training:
931
+
932
+ def create_custom_forward(module):
933
+ def custom_forward(*inputs):
934
+ # None for past_key_value
935
+ return module(*inputs)
936
+
937
+ return custom_forward
938
+
939
+ hidden_states, hidden_states2, residual = torch.utils.checkpoint.checkpoint(
940
+ create_custom_forward(layer),
941
+ hidden_states,
942
+ hidden_states2,
943
+ residual,
944
+ attention_mask,
945
+ None,
946
+ None,
947
+ is_padded_inputs,
948
+ # if you freeze ANY layers, you need `use_reentrant=False`
949
+ # https://github.com/huggingface/transformers/issues/21381
950
+ # https://discuss.pytorch.org/t/checkpoint-with-no-grad-requiring-inputs-problem/19117/7
951
+ use_reentrant=False,
952
+ )
953
+
954
+ else:
955
+ hidden_states, hidden_states2, residual = layer(
956
+ hidden_states,
957
+ hidden_states2,
958
+ residual,
959
+ attention_mask,
960
+ position_ids,
961
+ None,
962
+ is_padded_inputs,
963
+ output_attentions,
964
+ use_cache,
965
+ )
966
+ return hidden_states
967
+
968
+
969
+ class NomicBertPooler(nn.Module):
970
+ def __init__(self, config):
971
+ super().__init__()
972
+ self.dense = nn.Linear(config.n_embd, config.n_embd)
973
+ self.activation = nn.Tanh()
974
+
975
+ def forward(self, hidden_states, pool=True):
976
+ # We "pool" the model by simply taking the hidden state corresponding
977
+ # to the first token.
978
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
979
+ pooled_output = self.dense(first_token_tensor)
980
+ pooled_output = self.activation(pooled_output)
981
+ return pooled_output
982
+
983
+
984
+ class NomicBertPredictionHeadTransform(nn.Module):
985
+ def __init__(self, config):
986
+ super().__init__()
987
+ self.dense = nn.Linear(config.n_embd, config.n_embd, bias=config.mlp_fc1_bias)
988
+ approximate = "tanh" if config.activation_function in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
989
+ if config.activation_function == "swiglu":
990
+ self.transform_act_fn = F.silu
991
+ else:
992
+ self.transform_act_fn = nn.GELU(approximate=approximate)
993
+
994
+ self.layer_norm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
995
+
996
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
997
+ hidden_states = self.dense(hidden_states)
998
+ hidden_states = self.transform_act_fn(hidden_states)
999
+ hidden_states = self.layer_norm(hidden_states)
1000
+
1001
+ return hidden_states
1002
+
1003
+
1004
+ class NomicBertLMPredictionHead(nn.Module):
1005
+ def __init__(self, config):
1006
+ super().__init__()
1007
+
1008
+ self.transform = NomicBertPredictionHeadTransform(config)
1009
+
1010
+ self.decoder = nn.Linear(config.n_embd, config.vocab_size, bias=config.mlp_fc1_bias)
1011
+
1012
+ def forward(self, hidden_states):
1013
+ hidden_states = self.transform(hidden_states)
1014
+ hidden_states = self.decoder(hidden_states)
1015
+ return hidden_states
1016
+
1017
+
1018
+ class NomicBertPreTrainingHeads(nn.Module):
1019
+ def __init__(self, config):
1020
+ super().__init__()
1021
+ self.predictions = NomicBertLMPredictionHead(config)
1022
+
1023
+ def forward(self, sequence_output):
1024
+ prediction_scores = self.predictions(sequence_output)
1025
+ return prediction_scores
1026
+
1027
+
1028
+ class NomicBertModel(NomicBertPreTrainedModel):
1029
+ def __init__(self, config: GPT2Config, add_pooling_layer=True):
1030
+ super().__init__(config)
1031
+ self.pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
1032
+ if config.vocab_size % self.pad_vocab_size_multiple != 0:
1033
+ config.vocab_size += self.pad_vocab_size_multiple - (config.vocab_size % self.pad_vocab_size_multiple)
1034
+
1035
+ assert config.activation_function in [
1036
+ "gelu",
1037
+ "gelu_new",
1038
+ "gelu_fast",
1039
+ "gelu_pytorch_tanh",
1040
+ "swiglu",
1041
+ "geglu",
1042
+ "glu",
1043
+ ]
1044
+
1045
+ self.embeddings = NomicBertEmbeddings(config)
1046
+ self.emb_drop = nn.Dropout(config.resid_pdrop)
1047
+ self.emb_ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1048
+ self.encoder = NomicBertEncoder(config)
1049
+ self.pooler = NomicBertPooler(config) if add_pooling_layer else None
1050
+
1051
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1052
+
1053
+ def forward(
1054
+ self,
1055
+ input_ids,
1056
+ attention_mask=None,
1057
+ token_type_ids=None,
1058
+ position_ids=None,
1059
+ return_dict=None,
1060
+ ):
1061
+ if token_type_ids is None:
1062
+ token_type_ids = torch.zeros_like(input_ids)
1063
+ hidden_states = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)
1064
+ hidden_states = self.emb_ln(hidden_states)
1065
+ hidden_states = self.emb_drop(hidden_states)
1066
+
1067
+ # FailureLens: transformers 5 removed get_extended_attention_mask.
1068
+ if attention_mask is not None:
1069
+ if attention_mask.dim() == 2:
1070
+ attention_mask = attention_mask[:, None, None, :].to(dtype=torch.float32)
1071
+ attention_mask = (1.0 - attention_mask) * torch.finfo(torch.float32).min
1072
+ elif attention_mask.dim() != 4:
1073
+ raise ValueError("Expected a 2-D or 4-D attention mask")
1074
+
1075
+ sequence_output = self.encoder(hidden_states, attention_mask=attention_mask, return_dict=return_dict)
1076
+
1077
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1078
+
1079
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1080
+ last_hidden_state=sequence_output,
1081
+ pooler_output=pooled_output,
1082
+ )
1083
+
1084
+
1085
+ class NomicBertForPreTraining(NomicBertPreTrainedModel):
1086
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1087
+
1088
+ def __init__(self, config: GPT2Config):
1089
+ super().__init__(config)
1090
+
1091
+ self.bert = NomicBertModel(config, add_pooling_layer=getattr(config, "add_pooling_layer", False))
1092
+ self.cls = NomicBertPreTrainingHeads(config)
1093
+ self.mlm_loss = nn.CrossEntropyLoss()
1094
+
1095
+ # Initialize weights and apply final processing
1096
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1097
+ self.tie_weights()
1098
+
1099
+ def tie_weights(self):
1100
+ self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight
1101
+
1102
+ def forward(
1103
+ self,
1104
+ input_ids,
1105
+ position_ids=None,
1106
+ token_type_ids=None,
1107
+ attention_mask=None,
1108
+ labels=None,
1109
+ ):
1110
+ """
1111
+ If labels are provided, they must be -100 for masked out tokens (as specified in the attention
1112
+ mask).
1113
+ Outputs:
1114
+ if `labels` and `next_sentence_label` are not `None`:
1115
+ Outputs the total_loss which is the sum of the masked language modeling loss and the next
1116
+ sentence classification loss.
1117
+ if `labels` or `next_sentence_label` is `None`:
1118
+ Outputs a tuple comprising
1119
+ - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
1120
+ - the next sentence classification logits of shape [batch_size, 2].
1121
+ """
1122
+ outputs = self.bert(
1123
+ input_ids,
1124
+ position_ids=position_ids,
1125
+ token_type_ids=token_type_ids,
1126
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1127
+ )
1128
+ sequence_output, _ = outputs.last_hidden_state, outputs.pooler_output
1129
+
1130
+ prediction_scores = self.cls(sequence_output)
1131
+
1132
+ total_loss = None
1133
+ if labels is not None:
1134
+ masked_lm_loss = self.mlm_loss(
1135
+ rearrange(prediction_scores, "... v -> (...) v"),
1136
+ rearrange(labels, "... -> (...)"),
1137
+ )
1138
+ total_loss = masked_lm_loss.float()
1139
+
1140
+ return MaskedLMOutput(
1141
+ loss=total_loss,
1142
+ logits=prediction_scores,
1143
+ hidden_states=outputs.hidden_states,
1144
+ attentions=None,
1145
+ )
1146
+
1147
+
1148
+ class NomicBertForSequenceClassification(NomicBertPreTrainedModel):
1149
+ def __init__(self, config):
1150
+ super().__init__(config)
1151
+ self.num_labels = config.num_labels
1152
+ self.config = config
1153
+
1154
+ self.bert = NomicBertModel(config)
1155
+ classifier_dropout = getattr(config, "classifier_dropout", config.embd_pdrop)
1156
+ self.dropout = nn.Dropout(classifier_dropout)
1157
+ self.classifier = nn.Linear(config.n_embd, config.num_labels)
1158
+
1159
+ # Initialize weights and apply final processing
1160
+ self.post_init()
1161
+
1162
+ def forward(
1163
+ self,
1164
+ input_ids: Optional[torch.Tensor] = None,
1165
+ attention_mask: Optional[torch.Tensor] = None,
1166
+ token_type_ids: Optional[torch.Tensor] = None,
1167
+ position_ids: Optional[torch.Tensor] = None,
1168
+ head_mask: Optional[torch.Tensor] = None,
1169
+ inputs_embeds: Optional[torch.Tensor] = None,
1170
+ labels: Optional[torch.Tensor] = None,
1171
+ output_attentions: Optional[bool] = None,
1172
+ output_hidden_states: Optional[bool] = None,
1173
+ return_dict: Optional[bool] = None,
1174
+ ):
1175
+ r"""
1176
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1177
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1178
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1179
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1180
+ """
1181
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1182
+ outputs = self.bert(
1183
+ input_ids,
1184
+ position_ids=position_ids,
1185
+ token_type_ids=token_type_ids,
1186
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1187
+ )
1188
+
1189
+ pooled_output = outputs[1]
1190
+
1191
+ pooled_output = self.dropout(pooled_output)
1192
+ logits = self.classifier(pooled_output)
1193
+
1194
+ loss = None
1195
+ if labels is not None:
1196
+ if self.config.problem_type is None:
1197
+ if self.num_labels == 1:
1198
+ self.config.problem_type = "regression"
1199
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1200
+ self.config.problem_type = "single_label_classification"
1201
+ else:
1202
+ self.config.problem_type = "multi_label_classification"
1203
+
1204
+ if self.config.problem_type == "regression":
1205
+ loss_fct = nn.MSELoss()
1206
+ if self.num_labels == 1:
1207
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1208
+ else:
1209
+ loss = loss_fct(logits, labels)
1210
+ elif self.config.problem_type == "single_label_classification":
1211
+ loss_fct = nn.CrossEntropyLoss()
1212
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1213
+ elif self.config.problem_type == "multi_label_classification":
1214
+ loss_fct = nn.BCEWithLogitsLoss()
1215
+ loss = loss_fct(logits, labels)
1216
+ if not return_dict:
1217
+ output = (logits,) + outputs[2:]
1218
+ return ((loss,) + output) if loss is not None else output
1219
+
1220
+ return SequenceClassifierOutput(
1221
+ loss=loss,
1222
+ logits=logits,
1223
+ hidden_states=outputs.hidden_states,
1224
+ attentions=outputs.attentions,
1225
+ )
modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
sentence_bert_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 8192,
3
+ "do_lower_case": false,
4
+ "model_args": {
5
+ "add_pooling_layer": false,
6
+ "safe_serialization": true
7
+ }
8
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "additional_special_tokens": [],
45
+ "clean_up_tokenization_spaces": true,
46
+ "cls_token": "[CLS]",
47
+ "do_lower_case": true,
48
+ "mask_token": "[MASK]",
49
+ "max_length": 512,
50
+ "model_max_length": 8192,
51
+ "pad_to_multiple_of": null,
52
+ "pad_token": "[PAD]",
53
+ "pad_token_type_id": 0,
54
+ "padding_side": "right",
55
+ "sep_token": "[SEP]",
56
+ "stride": 0,
57
+ "strip_accents": null,
58
+ "tokenize_chinese_chars": true,
59
+ "tokenizer_class": "BertTokenizer",
60
+ "truncation_side": "right",
61
+ "truncation_strategy": "longest_first",
62
+ "unk_token": "[UNK]"
63
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff