mnm-matin commited on
Commit
88b959f
·
verified ·
1 Parent(s): 18c2ab8

Initial model release

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ docs/technical-report.pdf filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OpenMDW License Agreement, version 1.1 (OpenMDW-1.1)
2
+
3
+ By exercising rights granted to you under this agreement, you accept and agree
4
+ to its terms.
5
+
6
+ As used in this agreement, "Model Materials" means the materials provided to
7
+ you under this agreement, consisting of: (1) one or more machine learning
8
+ models (including architecture and parameters); and (2) all related artifacts
9
+ (including associated data, documentation and software) that are provided to
10
+ you hereunder.
11
+
12
+ Subject to your compliance with this agreement, permission is hereby granted,
13
+ free of charge, to deal in the Model Materials without restriction, including
14
+ under all copyright, patent, database, and trade secret rights included or
15
+ embodied therein.
16
+
17
+ If you distribute any portion of the Model Materials, you shall retain in your
18
+ distribution (1) a copy of this agreement, and (2) all copyright notices and
19
+ other notices of origin included in the Model Materials that are applicable to
20
+ your distribution.
21
+
22
+ If you file, maintain, or voluntarily participate in a lawsuit against any
23
+ person or entity asserting that the Model Materials directly or indirectly
24
+ infringe any patent or copyright, then all rights and grants made to you
25
+ hereunder are terminated, unless that lawsuit was in response to a
26
+ corresponding lawsuit first brought against you.
27
+
28
+ This agreement does not impose any restrictions or obligations with respect to
29
+ any use, modification, or sharing of any outputs generated by using the Model
30
+ Materials.
31
+
32
+ THE MODEL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
33
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE
35
+ ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL
36
+ TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.
37
+
38
+ YOU ARE SOLELY RESPONSIBLE FOR (1) CLEARING RIGHTS OF OTHER PERSONS THAT MAY
39
+ APPLY TO THE MODEL MATERIALS OR ANY USE THEREOF, INCLUDING WITHOUT LIMITATION
40
+ ANY PERSON'S COPYRIGHTS OR OTHER RIGHTS INCLUDED OR EMBODIED IN THE MODEL
41
+ MATERIALS; (2) OBTAINING ANY NECESSARY CONSENTS, PERMISSIONS OR OTHER RIGHTS
42
+ REQUIRED FOR ANY USE OF THE MODEL MATERIALS; OR (3) PERFORMING ANY DUE
43
+ DILIGENCE OR UNDERTAKING ANY OTHER INVESTIGATIONS INTO THE MODEL MATERIALS OR
44
+ ANYTHING INCORPORATED OR EMBODIED THEREIN.
45
+
46
+ IN NO EVENT SHALL THE PROVIDERS OF THE MODEL MATERIALS BE LIABLE FOR ANY CLAIM,
47
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
48
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MODEL MATERIALS, THE
49
+ USE THEREOF OR OTHER DEALINGS THEREIN.
50
+
51
+ ========================================================================
52
+ Third-party license: Gemma 4 backbone
53
+ ========================================================================
54
+
55
+ The Gemma 4 backbone is distributed under the following Apache License,
56
+ Version 2.0. Its terms and applicable upstream notices remain in effect.
57
+
58
+
59
+ Apache License
60
+ Version 2.0, January 2004
61
+ http://www.apache.org/licenses/
62
+
63
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
64
+
65
+ 1. Definitions.
66
+
67
+ "License" shall mean the terms and conditions for use, reproduction,
68
+ and distribution as defined by Sections 1 through 9 of this document.
69
+
70
+ "Licensor" shall mean the copyright owner or entity authorized by
71
+ the copyright owner that is granting the License.
72
+
73
+ "Legal Entity" shall mean the union of the acting entity and all
74
+ other entities that control, are controlled by, or are under common
75
+ control with that entity. For the purposes of this definition,
76
+ "control" means (i) the power, direct or indirect, to cause the
77
+ direction or management of such entity, whether by contract or
78
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
79
+ outstanding shares, or (iii) beneficial ownership of such entity.
80
+
81
+ "You" (or "Your") shall mean an individual or Legal Entity
82
+ exercising permissions granted by this License.
83
+
84
+ "Source" form shall mean the preferred form for making modifications,
85
+ including but not limited to software source code, documentation
86
+ source, and configuration files.
87
+
88
+ "Object" form shall mean any form resulting from mechanical
89
+ transformation or translation of a Source form, including but
90
+ not limited to compiled object code, generated documentation,
91
+ and conversions to other media types.
92
+
93
+ "Work" shall mean the work of authorship, whether in Source or
94
+ Object form, made available under the License, as indicated by a
95
+ copyright notice that is included in or attached to the work
96
+ (an example is provided in the Appendix below).
97
+
98
+ "Derivative Works" shall mean any work, whether in Source or Object
99
+ form, that is based on (or derived from) the Work and for which the
100
+ editorial revisions, annotations, elaborations, or other modifications
101
+ represent, as a whole, an original work of authorship. For the purposes
102
+ of this License, Derivative Works shall not include works that remain
103
+ separable from, or merely link (or bind by name) to the interfaces of,
104
+ the Work and Derivative Works thereof.
105
+
106
+ "Contribution" shall mean any work of authorship, including
107
+ the original version of the Work and any modifications or additions
108
+ to that Work or Derivative Works thereof, that is intentionally
109
+ submitted to Licensor for inclusion in the Work by the copyright owner
110
+ or by an individual or Legal Entity authorized to submit on behalf of
111
+ the copyright owner. For the purposes of this definition, "submitted"
112
+ means any form of electronic, verbal, or written communication sent
113
+ to the Licensor or its representatives, including but not limited to
114
+ communication on electronic mailing lists, source code control systems,
115
+ and issue tracking systems that are managed by, or on behalf of, the
116
+ Licensor for the purpose of discussing and improving the Work, but
117
+ excluding communication that is conspicuously marked or otherwise
118
+ designated in writing by the copyright owner as "Not a Contribution."
119
+
120
+ "Contributor" shall mean Licensor and any individual or Legal Entity
121
+ on behalf of whom a Contribution has been received by Licensor and
122
+ subsequently incorporated within the Work.
123
+
124
+ 2. Grant of Copyright License. Subject to the terms and conditions of
125
+ this License, each Contributor hereby grants to You a perpetual,
126
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
127
+ copyright license to reproduce, prepare Derivative Works of,
128
+ publicly display, publicly perform, sublicense, and distribute the
129
+ Work and such Derivative Works in Source or Object form.
130
+
131
+ 3. Grant of Patent License. Subject to the terms and conditions of
132
+ this License, each Contributor hereby grants to You a perpetual,
133
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
134
+ (except as stated in this section) patent license to make, have made,
135
+ use, offer to sell, sell, import, and otherwise transfer the Work,
136
+ where such license applies only to those patent claims licensable
137
+ by such Contributor that are necessarily infringed by their
138
+ Contribution(s) alone or by combination of their Contribution(s)
139
+ with the Work to which such Contribution(s) was submitted. If You
140
+ institute patent litigation against any entity (including a
141
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
142
+ or a Contribution incorporated within the Work constitutes direct
143
+ or contributory patent infringement, then any patent licenses
144
+ granted to You under this License for that Work shall terminate
145
+ as of the date such litigation is filed.
146
+
147
+ 4. Redistribution. You may reproduce and distribute copies of the
148
+ Work or Derivative Works thereof in any medium, with or without
149
+ modifications, and in Source or Object form, provided that You
150
+ meet the following conditions:
151
+
152
+ (a) You must give any other recipients of the Work or
153
+ Derivative Works a copy of this License; and
154
+
155
+ (b) You must cause any modified files to carry prominent notices
156
+ stating that You changed the files; and
157
+
158
+ (c) You must retain, in the Source form of any Derivative Works
159
+ that You distribute, all copyright, patent, trademark, and
160
+ attribution notices from the Source form of the Work,
161
+ excluding those notices that do not pertain to any part of
162
+ the Derivative Works; and
163
+
164
+ (d) If the Work includes a "NOTICE" text file as part of its
165
+ distribution, then any Derivative Works that You distribute must
166
+ include a readable copy of the attribution notices contained
167
+ within such NOTICE file, excluding those notices that do not
168
+ pertain to any part of the Derivative Works, in at least one
169
+ of the following places: within a NOTICE text file distributed
170
+ as part of the Derivative Works; within the Source form or
171
+ documentation, if provided along with the Derivative Works; or,
172
+ within a display generated by the Derivative Works, if and
173
+ wherever such third-party notices normally appear. The contents
174
+ of the NOTICE file are for informational purposes only and
175
+ do not modify the License. You may add Your own attribution
176
+ notices within Derivative Works that You distribute, alongside
177
+ or as an addendum to the NOTICE text from the Work, provided
178
+ that such additional attribution notices cannot be construed
179
+ as modifying the License.
180
+
181
+ You may add Your own copyright statement to Your modifications and
182
+ may provide additional or different license terms and conditions
183
+ for use, reproduction, or distribution of Your modifications, or
184
+ for any such Derivative Works as a whole, provided Your use,
185
+ reproduction, and distribution of the Work otherwise complies with
186
+ the conditions stated in this License.
187
+
188
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
189
+ any Contribution intentionally submitted for inclusion in the Work
190
+ by You to the Licensor shall be under the terms and conditions of
191
+ this License, without any additional terms or conditions.
192
+ Notwithstanding the above, nothing herein shall supersede or modify
193
+ the terms of any separate license agreement you may have executed
194
+ with Licensor regarding such Contributions.
195
+
196
+ 6. Trademarks. This License does not grant permission to use the trade
197
+ names, trademarks, service marks, or product names of the Licensor,
198
+ except as required for reasonable and customary use in describing the
199
+ origin of the Work and reproducing the content of the NOTICE file.
200
+
201
+ 7. Disclaimer of Warranty. Unless required by applicable law or
202
+ agreed to in writing, Licensor provides the Work (and each
203
+ Contributor provides its Contributions) on an "AS IS" BASIS,
204
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
205
+ implied, including, without limitation, any warranties or conditions
206
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
207
+ PARTICULAR PURPOSE. You are solely responsible for determining the
208
+ appropriateness of using or redistributing the Work and assume any
209
+ risks associated with Your exercise of permissions under this License.
210
+
211
+ 8. Limitation of Liability. In no event and under no legal theory,
212
+ whether in tort (including negligence), contract, or otherwise,
213
+ unless required by applicable law (such as deliberate and grossly
214
+ negligent acts) or agreed to in writing, shall any Contributor be
215
+ liable to You for damages, including any direct, indirect, special,
216
+ incidental, or consequential damages of any character arising as a
217
+ result of this License or out of the use or inability to use the
218
+ Work (including but not limited to damages for loss of goodwill,
219
+ work stoppage, computer failure or malfunction, or any and all
220
+ other commercial damages or losses), even if such Contributor
221
+ has been advised of the possibility of such damages.
222
+
223
+ 9. Accepting Warranty or Additional Liability. While redistributing
224
+ the Work or Derivative Works thereof, You may choose to offer,
225
+ and charge a fee for, acceptance of support, warranty, indemnity,
226
+ or other liability obligations and/or rights consistent with this
227
+ License. However, in accepting such obligations, You may act only
228
+ on Your own behalf and on Your sole responsibility, not on behalf
229
+ of any other Contributor, and only if You agree to indemnify,
230
+ defend, and hold each Contributor harmless for any liability
231
+ incurred by, or claims asserted against, such Contributor by reason
232
+ of your accepting any such warranty or additional liability.
233
+
234
+ END OF TERMS AND CONDITIONS
235
+
236
+ APPENDIX: How to apply the Apache License to your work.
237
+
238
+ To apply the Apache License to your work, attach the following
239
+ boilerplate notice, with the fields enclosed by brackets "[]"
240
+ replaced with your own identifying information. (Don't include
241
+ the brackets!) The text should be enclosed in the appropriate
242
+ comment syntax for the file format. We also recommend that a
243
+ file or class name and description of purpose be included on the
244
+ same "printed page" as the copyright notice for easier
245
+ identification within third-party archives.
246
+
247
+ Copyright [yyyy] [name of copyright owner]
248
+
249
+ Licensed under the Apache License, Version 2.0 (the "License");
250
+ you may not use this file except in compliance with the License.
251
+ You may obtain a copy of the License at
252
+
253
+ http://www.apache.org/licenses/LICENSE-2.0
254
+
255
+ Unless required by applicable law or agreed to in writing, software
256
+ distributed under the License is distributed on an "AS IS" BASIS,
257
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
258
+ See the License for the specific language governing permissions and
259
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: openmdw-1.1
3
+ language:
4
+ - de
5
+ - en
6
+ library_name: sentence-transformers
7
+ pipeline_tag: sentence-similarity
8
+ base_model: google/gemma-4-E2B-it
9
+ base_model_relation: finetune
10
+ tags:
11
+ - sentence-transformers
12
+ - feature-extraction
13
+ - text-embeddings
14
+ - german
15
+ - late-interaction
16
+ - mteb
17
+ ---
18
+
19
+ <div align="center">
20
+ <a href="https://hyper3labs.com">
21
+ <img src="https://hyper3labs.com/brand-assets/hyper3labs-logo-primary.svg" width="64" height="64" alt="hyper³labs logo">
22
+ </a>
23
+ <p><strong>hyper³labs</strong></p>
24
+ <h1>hyper3-embed-deu</h1>
25
+ <p>
26
+ <a href="https://hyper3labs.com">Website</a> ·
27
+ <a href="https://github.com/Hyper3Labs">GitHub</a> ·
28
+ <a href="https://huggingface.co/hyper3labs">Hugging Face</a> ·
29
+ <a href="https://discord.gg/Za3rBkTPSf">Discord</a> ·
30
+ <a href="https://x.com/hyper3labs">X</a>
31
+ </p>
32
+ </div>
33
+
34
+ **hyper3-embed-deu** is a German text embedding model from [hyper³labs](https://hyper3labs.com), fine-tuned from [Gemma 4 E2B](https://huggingface.co/google/gemma-4-E2B-it). A single bidirectional encoder produces **1,536-dimensional dense embeddings** for vector search, clustering, and classification, alongside **128-dimensional token vectors** for fused dense + MaxSim retrieval over long documents.
35
+
36
+ | Property | Value |
37
+ |---|---|
38
+ | Parameters | 4.66B total (1.91B active transformer + heads; 2.75B embeddings) |
39
+ | Dense output | 1,536 dimensions, L2-normalized, cosine similarity (4,096-token limit) |
40
+ | Fused retrieval | 0.25 dense + 0.75 MaxSim, mixing full document (4,096 tok) and best 512-token window (stride 256) |
41
+ | Weights | BF16 backbone, FP32 heads (~8.75 GiB GPU memory; ~9.43 GB download) |
42
+ | Languages | German; English in cross-lingual pairs |
43
+
44
+ ## Quick start
45
+
46
+ ```bash
47
+ pip install torch==2.14.0 transformers==5.17.0 sentence-transformers==6.1.0 \
48
+ huggingface_hub==1.33.0 safetensors==0.8.0 tokenizers==0.23.3
49
+ ```
50
+
51
+ ### Dense embeddings
52
+
53
+ Use with any vector database (Qdrant, Milvus, pgvector) or for clustering, classification, and similarity:
54
+
55
+ ```python
56
+ from sentence_transformers import SentenceTransformer
57
+
58
+ model = SentenceTransformer(
59
+ "hyper3labs/hyper3-embed-deu",
60
+ revision="v1",
61
+ trust_remote_code=True,
62
+ )
63
+
64
+ queries = ["Welche Unterlagen brauche ich für die Anmeldung einer Wohnung?"]
65
+ documents = [
66
+ "Für die Anmeldung benötigen Sie einen Ausweis und die Wohnungsgeberbestätigung.",
67
+ "Die Bibliothek ist montags bis freitags geöffnet.",
68
+ ]
69
+
70
+ q = model.encode_query(queries)
71
+ d = model.encode_document(documents)
72
+ print(model.similarity(q, d))
73
+ ```
74
+
75
+ Retrieval queries automatically receive a search instruction; documents use no prefix. For symmetric or classification tasks, pass `prompt_name="sts"`, `"clustering"`, `"classification"`, `"pair_classification"`, or a task name from [`config.json`](config.json).
76
+
77
+ ### Fused long-document retrieval
78
+
79
+ Score a candidate set using both the dense embedding and token-level MaxSim across overlapping 512-token windows:
80
+
81
+ ```python
82
+ scores = model[0].model.score_multivector(queries, documents, batch_size=8)
83
+ print(scores.cpu().tolist())
84
+ ```
85
+
86
+ <details>
87
+ <summary><strong>Index a corpus once, or load via Transformers AutoModel</strong></summary>
88
+
89
+ To precompute document and window representations once and score incoming queries against them:
90
+
91
+ ```python
92
+ import torch
93
+
94
+ core = model[0].model
95
+ doc_dense, doc_tokens = core.encode_with_tokens(documents)
96
+ windows, owner = core.document_windows(documents)
97
+ win_dense, win_tokens = core.encode_with_tokens(windows, max_length=576)
98
+ owner_t = torch.tensor(owner)
99
+
100
+ q_dense, q_tokens = core.encode_with_tokens(queries, prompt_name="query", max_length=1024)
101
+
102
+ scores = core.fuse_scores(
103
+ dense_full=q_dense @ doc_dense.T,
104
+ dense_window=core.best_per_document(q_dense @ win_dense.T, owner_t, len(documents)),
105
+ maxsim_full=core.maxsim_scores(q_tokens, doc_tokens),
106
+ maxsim_window=core.best_per_document(core.maxsim_scores(q_tokens, win_tokens), owner_t, len(documents)),
107
+ )
108
+ ```
109
+
110
+ To load directly through `transformers` instead of Sentence Transformers:
111
+
112
+ ```python
113
+ import torch
114
+ from transformers import AutoModel
115
+
116
+ core = AutoModel.from_pretrained("hyper3labs/hyper3-embed-deu", revision="v1", trust_remote_code=True)
117
+ core.to("cuda" if torch.cuda.is_available() else "cpu")
118
+ embeddings = core.encode(queries, prompt_name="query")
119
+ ```
120
+
121
+ On CUDA hosts, the backbone loads in BF16 (~8.75 GiB); on CPU-only hosts it defaults to FP32 (~17.4 GiB). To set precision explicitly, pass `model_kwargs={"dtype": torch.bfloat16}` (do not call `.half()`, as pooling and MaxSim heads run in FP32).
122
+
123
+ </details>
124
+
125
+ ## License
126
+
127
+ Weights, code, and documentation are released under [OpenMDW-1.1](LICENSE) (which includes the Apache-2.0 license for the Gemma 4 base model).
128
+
129
+ ## Citation
130
+
131
+ ```bibtex
132
+ @misc{hyper3embeddeu2026,
133
+ title = {hyper3-embed-deu: German Text Embeddings from Gemma 4},
134
+ author = {hyper3labs},
135
+ year = {2026},
136
+ publisher = {Hugging Face},
137
+ url = {https://huggingface.co/hyper3labs/hyper3-embed-deu}
138
+ }
139
+ ```
140
+
141
+ [Website](https://hyper3labs.com) · [Discord](https://discord.gg/Za3rBkTPSf) · [GitHub](https://github.com/Hyper3Labs)
backbone/config.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Gemma4TextModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_k_eq_v": false,
8
+ "bos_token_id": 2,
9
+ "dtype": "bfloat16",
10
+ "enable_moe_block": false,
11
+ "eos_token_id": 1,
12
+ "expert_intermediate_size": null,
13
+ "final_logit_softcapping": 30.0,
14
+ "global_head_dim": 512,
15
+ "head_dim": 256,
16
+ "hidden_activation": "gelu_pytorch_tanh",
17
+ "hidden_size": 1536,
18
+ "hidden_size_per_layer_input": 256,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 6144,
21
+ "is_causal": false,
22
+ "layer_types": [
23
+ "sliding_attention",
24
+ "sliding_attention",
25
+ "sliding_attention",
26
+ "sliding_attention",
27
+ "full_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "sliding_attention",
31
+ "sliding_attention",
32
+ "full_attention",
33
+ "sliding_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "sliding_attention",
37
+ "full_attention",
38
+ "sliding_attention",
39
+ "sliding_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "sliding_attention",
46
+ "sliding_attention",
47
+ "full_attention",
48
+ "sliding_attention",
49
+ "sliding_attention",
50
+ "sliding_attention",
51
+ "sliding_attention",
52
+ "full_attention",
53
+ "sliding_attention",
54
+ "sliding_attention",
55
+ "sliding_attention",
56
+ "sliding_attention",
57
+ "full_attention"
58
+ ],
59
+ "max_position_embeddings": 131072,
60
+ "model_type": "gemma4_text",
61
+ "moe_intermediate_size": null,
62
+ "num_attention_heads": 8,
63
+ "num_experts": null,
64
+ "num_global_key_value_heads": null,
65
+ "num_hidden_layers": 35,
66
+ "num_key_value_heads": 1,
67
+ "num_kv_shared_layers": 20,
68
+ "pad_token_id": 0,
69
+ "rms_norm_eps": 1e-06,
70
+ "rope_parameters": {
71
+ "full_attention": {
72
+ "partial_rotary_factor": 0.25,
73
+ "rope_theta": 1000000.0,
74
+ "rope_type": "proportional"
75
+ },
76
+ "sliding_attention": {
77
+ "rope_theta": 10000.0,
78
+ "rope_type": "default"
79
+ }
80
+ },
81
+ "sliding_window": 257,
82
+ "tie_word_embeddings": true,
83
+ "top_k_experts": null,
84
+ "transformers_version": "5.14.1",
85
+ "use_bidirectional_attention": "all",
86
+ "use_cache": false,
87
+ "use_double_wide_mlp": true,
88
+ "vocab_size": 262144,
89
+ "vocab_size_per_layer_input": 262144
90
+ }
backbone/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b33b2ec7e6391cf4278f33cf5e5a1d358f9fad9ae19510b53f6a67cf9f36b6c
3
+ size 9257198294
config.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Hyper3EmbedModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_hyper3_embed.Hyper3EmbedConfig",
7
+ "AutoModel": "modeling_hyper3_embed.Hyper3EmbedModel"
8
+ },
9
+ "model_type": "hyper3_embed",
10
+ "backbone_subfolder": "backbone",
11
+ "embedding_dim": 1536,
12
+ "max_length": 4096,
13
+ "transformers_version": "5.17.0",
14
+ "embedding_config": {
15
+ "base_model_id": "google/gemma-4-E2B-it",
16
+ "hidden_size": 1536,
17
+ "pooled_size": 1536,
18
+ "projection_dim": 1536,
19
+ "projection_enabled": false,
20
+ "pooling": "latent_cross_attention_mean",
21
+ "text_transform": "none",
22
+ "attention_mode": "bidirectional",
23
+ "append_eos": true,
24
+ "latent_count": 128,
25
+ "latent_num_heads": 8,
26
+ "latent_head_dim": 128,
27
+ "latent_ffn_mult": 4,
28
+ "latent_output_normalize": true,
29
+ "pooler_compute_dtype": "fp32",
30
+ "training_mode": "full",
31
+ "multivec_dim": 128,
32
+ "multivec_token_mask": "content"
33
+ },
34
+ "prompt_config": {
35
+ "protocol": "uniform4096-v1",
36
+ "max_length": 4096,
37
+ "task_max_lengths": {},
38
+ "type_prompts": {
39
+ "retrieval": {
40
+ "query": "Instruct: Given a search query, retrieve relevant passages.\nQuery: ",
41
+ "positive": ""
42
+ },
43
+ "bitext": {
44
+ "query": "Instruct: Retrieve translation-equivalent text.\nQuery: ",
45
+ "positive": "Instruct: Retrieve translation-equivalent text.\nQuery: "
46
+ },
47
+ "clustering": {
48
+ "query": "Instruct: Group texts by topic.\nQuery: ",
49
+ "positive": "Instruct: Group texts by topic.\nQuery: "
50
+ },
51
+ "sts": {
52
+ "query": "Instruct: Retrieve semantically similar text.\nQuery: ",
53
+ "positive": "Instruct: Retrieve semantically similar text.\nQuery: "
54
+ },
55
+ "classification": {
56
+ "query": "Instruct: Classify the text.\nQuery: ",
57
+ "positive": ""
58
+ },
59
+ "pair_classification": {
60
+ "query": "Instruct: Determine whether texts have the same meaning.\nQuery: ",
61
+ "positive": "Instruct: Determine whether texts have the same meaning.\nQuery: "
62
+ }
63
+ },
64
+ "task_instructions": {
65
+ "AmazonCounterfactualClassification": "Classify a given Amazon customer review text as either counterfactual or not counterfactual.",
66
+ "AmazonReviewsClassification": "Classify the given Amazon review into its appropriate rating category.",
67
+ "BelebeleRetrieval": "Given a question, retrieve a passage in any language that answers the question.",
68
+ "BlurbsClusteringP2P": "Classify the given book title and blurb into its genre.",
69
+ "BlurbsClusteringS2S": "Classify the given book title into its genre.",
70
+ "FalseFriendsGermanEnglish": "Retrieve translations of the following text.",
71
+ "FloresBitextMining": "Retrieve translation-equivalent text.",
72
+ "GerDaLIR": "Given a legal query or passage, retrieve the court decision that addresses it.",
73
+ "GermanSTSBenchmark": "Retrieve semantically similar text.",
74
+ "MLQARetrieval": "Given a question, retrieve a passage in any language that answers the question.",
75
+ "MTOPDomainClassification": "Classify the intent domain of the given utterance in task-oriented conversation.",
76
+ "MTOPIntentClassification": "Classify the intent of the given utterance in task-oriented conversation.",
77
+ "MassiveIntentClassification": "Classify the intent of the given utterance in task-oriented conversation.",
78
+ "MassiveScenarioClassification": "Classify the scenario of the given utterance in task-oriented conversation.",
79
+ "MultiEURLEXMultilabelClassification": "Classify the given EU legal act into its EuroVoc subject domains.",
80
+ "MultiHateClassification": "Classify the given text as either hateful or not hateful.",
81
+ "NTREXBitextMining": "Retrieve translation-equivalent text.",
82
+ "RTE3": "Given a premise, retrieve a hypothesis that is entailed by the premise.",
83
+ "STS17": "Retrieve semantically similar text in English or German.",
84
+ "STS22.v2": "Retrieve semantically similar text.",
85
+ "SwissJudgementClassification": "Classify the given facts of a Swiss court case by whether the appeal was approved or dismissed.",
86
+ "TenKGnadClusteringP2P": "Classify the topic of the given text.",
87
+ "TenKGnadClusteringS2S": "Classify the topic of the given text.",
88
+ "XMarket": "Given a product name search, retrieve the corresponding product description.",
89
+ "XNLI": "Given a premise, retrieve a hypothesis that is entailed by the premise."
90
+ },
91
+ "instruction_template": "Instruct: {instruction}\nQuery: "
92
+ }
93
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "SentenceTransformer",
3
+ "__version__": {
4
+ "sentence_transformers": "6.1.0",
5
+ "transformers": "5.17.0",
6
+ "pytorch": "2.14.0"
7
+ },
8
+ "prompts": {
9
+ "query": "Instruct: Given a search query, retrieve relevant passages.\nQuery: ",
10
+ "document": "",
11
+ "bitext": "Instruct: Retrieve translation-equivalent text.\nQuery: ",
12
+ "clustering": "Instruct: Group texts by topic.\nQuery: ",
13
+ "sts": "Instruct: Retrieve semantically similar text.\nQuery: ",
14
+ "classification": "Instruct: Classify the text.\nQuery: ",
15
+ "pair_classification": "Instruct: Determine whether texts have the same meaning.\nQuery: ",
16
+ "AmazonCounterfactualClassification": "Instruct: Classify a given Amazon customer review text as either counterfactual or not counterfactual.\nQuery: ",
17
+ "AmazonReviewsClassification": "Instruct: Classify the given Amazon review into its appropriate rating category.\nQuery: ",
18
+ "BelebeleRetrieval": "Instruct: Given a question, retrieve a passage in any language that answers the question.\nQuery: ",
19
+ "BlurbsClusteringP2P": "Instruct: Classify the given book title and blurb into its genre.\nQuery: ",
20
+ "BlurbsClusteringS2S": "Instruct: Classify the given book title into its genre.\nQuery: ",
21
+ "FalseFriendsGermanEnglish": "Instruct: Retrieve translations of the following text.\nQuery: ",
22
+ "FloresBitextMining": "Instruct: Retrieve translation-equivalent text.\nQuery: ",
23
+ "GerDaLIR": "Instruct: Given a legal query or passage, retrieve the court decision that addresses it.\nQuery: ",
24
+ "GermanSTSBenchmark": "Instruct: Retrieve semantically similar text.\nQuery: ",
25
+ "MLQARetrieval": "Instruct: Given a question, retrieve a passage in any language that answers the question.\nQuery: ",
26
+ "MTOPDomainClassification": "Instruct: Classify the intent domain of the given utterance in task-oriented conversation.\nQuery: ",
27
+ "MTOPIntentClassification": "Instruct: Classify the intent of the given utterance in task-oriented conversation.\nQuery: ",
28
+ "MassiveIntentClassification": "Instruct: Classify the intent of the given utterance in task-oriented conversation.\nQuery: ",
29
+ "MassiveScenarioClassification": "Instruct: Classify the scenario of the given utterance in task-oriented conversation.\nQuery: ",
30
+ "MultiEURLEXMultilabelClassification": "Instruct: Classify the given EU legal act into its EuroVoc subject domains.\nQuery: ",
31
+ "MultiHateClassification": "Instruct: Classify the given text as either hateful or not hateful.\nQuery: ",
32
+ "NTREXBitextMining": "Instruct: Retrieve translation-equivalent text.\nQuery: ",
33
+ "RTE3": "Instruct: Given a premise, retrieve a hypothesis that is entailed by the premise.\nQuery: ",
34
+ "STS17": "Instruct: Retrieve semantically similar text in English or German.\nQuery: ",
35
+ "STS22.v2": "Instruct: Retrieve semantically similar text.\nQuery: ",
36
+ "SwissJudgementClassification": "Instruct: Classify the given facts of a Swiss court case by whether the appeal was approved or dismissed.\nQuery: ",
37
+ "TenKGnadClusteringP2P": "Instruct: Classify the topic of the given text.\nQuery: ",
38
+ "TenKGnadClusteringS2S": "Instruct: Classify the topic of the given text.\nQuery: ",
39
+ "XMarket": "Instruct: Given a product name search, retrieve the corresponding product description.\nQuery: ",
40
+ "XNLI": "Instruct: Given a premise, retrieve a hypothesis that is entailed by the premise.\nQuery: "
41
+ },
42
+ "default_prompt_name": null,
43
+ "similarity_fn_name": "cosine"
44
+ }
hyper3_embed_sentence_transformers.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import torch
6
+ from sentence_transformers.base.modules import InputModule
7
+
8
+ from .modeling_hyper3_embed import Hyper3EmbedModel, _resolve
9
+
10
+
11
+ class Hyper3EmbedSentenceTransformer(InputModule):
12
+ config_keys = ["max_seq_length"]
13
+
14
+ def __init__(self, model: Hyper3EmbedModel, max_seq_length: int = 4096) -> None:
15
+ super().__init__()
16
+ self.model = model
17
+ self.max_seq_length = max_seq_length
18
+ self.tokenizer = model.tokenizer
19
+
20
+ @classmethod
21
+ def load(
22
+ cls,
23
+ model_name_or_path: str,
24
+ subfolder: str = "",
25
+ token: bool | str | None = None,
26
+ cache_folder: str | None = None,
27
+ revision: str | None = None,
28
+ local_files_only: bool = False,
29
+ model_kwargs: dict[str, Any] | None = None,
30
+ **kwargs: Any,
31
+ ) -> Hyper3EmbedSentenceTransformer:
32
+ root = _resolve(model_name_or_path, revision, token, cache_folder, local_files_only)
33
+ model_kwargs = dict(model_kwargs or {})
34
+ dtype = model_kwargs.pop("dtype", model_kwargs.pop("torch_dtype", None))
35
+ if model_kwargs:
36
+ raise ValueError(
37
+ "Unsupported model_kwargs: "
38
+ + ", ".join(sorted(model_kwargs))
39
+ + ". This Sentence Transformers module accepts dtype only; use its device argument for placement."
40
+ )
41
+ model = Hyper3EmbedModel.from_pretrained(root / subfolder, dtype=dtype)
42
+ return cls(model, max_seq_length=model.config.max_length)
43
+
44
+ def preprocess(self, inputs: list[str], prompt: str | None = None, **kwargs: Any) -> dict[str, torch.Tensor]:
45
+ return self.model.tokenize(list(inputs), prompt or "", self.max_seq_length)
46
+
47
+ def forward(self, features: dict[str, torch.Tensor], **kwargs: Any) -> dict[str, torch.Tensor]:
48
+ features["sentence_embedding"] = self.model(
49
+ features["input_ids"], features["attention_mask"], features["pooling_mask"]
50
+ )
51
+ return features
52
+
53
+ def get_embedding_dimension(self) -> int:
54
+ return self.model.embedding_dim
55
+
56
+ get_sentence_embedding_dimension = get_embedding_dimension
57
+
58
+ def save(self, output_path: str, *args: Any, **kwargs: Any) -> None:
59
+ raise NotImplementedError("hyper3-embed-deu is released for inference.")
modeling_hyper3_embed.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+ from transformers import AutoConfig, AutoModel, AutoTokenizer, PretrainedConfig, PreTrainedModel
12
+
13
+ RELEASE_FILES = ("config.json", "pooler.safetensors", "backbone/config.json")
14
+ CHUNK_WINDOW, CHUNK_STRIDE, CHUNK_WEIGHT = 512, 256, 0.75
15
+
16
+
17
+ def chunk_mix_scores(queries: torch.Tensor, documents: torch.Tensor, windows: torch.Tensor, owner: torch.Tensor,
18
+ weight: float = CHUNK_WEIGHT, block: int = 256) -> torch.Tensor:
19
+ q = torch.as_tensor(queries).float()
20
+ full = q @ torch.as_tensor(documents).float().to(q.device).T
21
+ if len(windows) == 0:
22
+ return full
23
+ w = torch.as_tensor(windows).float().to(q.device)
24
+ owner = torch.as_tensor(owner, dtype=torch.long, device=q.device)
25
+ best = torch.full_like(full, -torch.inf)
26
+ for start in range(0, len(q), block):
27
+ part = q[start : start + block] @ w.T
28
+ best[start : start + block] = best[start : start + block].scatter_reduce(1, owner.expand(len(part), -1), part, "amax")
29
+ return torch.where(torch.isfinite(best), weight * best + (1 - weight) * full, full)
30
+
31
+
32
+ FUSE_DENSE_WEIGHT, FUSE_DENSE_WINDOW_WEIGHT, FUSE_MAXSIM_WINDOW_WEIGHT = 0.25, 0.5, 0.5
33
+ FUSE_DENSE_ONLY_MAX_TOKENS: int | None = None
34
+ FUSE_QUERY_MAX_LENGTH = 1024
35
+
36
+
37
+ def best_per_document(scores: torch.Tensor, owner: torch.Tensor, documents: int) -> torch.Tensor:
38
+ best = torch.full((scores.shape[0], documents), -torch.inf, device=scores.device)
39
+ return best.scatter_reduce(1, owner.to(scores.device).expand(scores.shape[0], -1), scores, "amax")
40
+
41
+
42
+ def maxsim_scores(queries: list[torch.Tensor], documents: list[torch.Tensor], query_block: int = 256,
43
+ budget: int | None = None) -> torch.Tensor:
44
+ device = queries[0].device
45
+ budget = budget or (2**28 if device.type == "cuda" else 2**24)
46
+
47
+ def pad(rows):
48
+ length = max(len(r) for r in rows)
49
+ out = torch.zeros(len(rows), length, rows[0].shape[1], device=device)
50
+ mask = torch.zeros(len(rows), length, dtype=torch.bool, device=device)
51
+ for i, r in enumerate(rows):
52
+ out[i, : len(r)], mask[i, : len(r)] = r.to(device).float(), True
53
+ return out, mask
54
+
55
+ q_order = sorted(range(len(queries)), key=lambda i: len(queries[i]))
56
+ d_order = sorted(range(len(documents)), key=lambda i: len(documents[i]))
57
+ result = torch.empty(len(queries), len(documents), device=device)
58
+ for qs in range(0, len(q_order), query_block):
59
+ q_index = q_order[qs : qs + query_block]
60
+ q, qm = pad([queries[i] for i in q_index])
61
+ rows = torch.tensor(q_index, device=device)
62
+ ds = 0
63
+ while ds < len(d_order):
64
+ longest = len(documents[d_order[min(ds + 255, len(d_order) - 1)]])
65
+ step = max(1, min(256, budget // (q.shape[0] * q.shape[1] * max(1, longest))))
66
+ d_index = d_order[ds : ds + step]
67
+ d, dm = pad([documents[i] for i in d_index])
68
+ sim = torch.einsum("qld,cmd->qclm", q, d).masked_fill_(~dm[None, :, None, :], -torch.inf).amax(-1)
69
+ sim = sim.masked_fill(~qm[:, None, :], 0).sum(-1) / qm.sum(-1, keepdim=True)
70
+ result[rows[:, None], torch.tensor(d_index, device=device)[None, :]] = sim
71
+ ds += step
72
+ return result
73
+
74
+
75
+ def fuse_scores(dense_full: torch.Tensor, dense_window: torch.Tensor, maxsim_full: torch.Tensor | None,
76
+ maxsim_window: torch.Tensor, document_tokens: torch.Tensor | None = None,
77
+ dense_weight: float = FUSE_DENSE_WEIGHT, dense_window_weight: float = FUSE_DENSE_WINDOW_WEIGHT,
78
+ maxsim_window_weight: float = FUSE_MAXSIM_WINDOW_WEIGHT,
79
+ dense_only_max_tokens: int | None = FUSE_DENSE_ONLY_MAX_TOKENS) -> torch.Tensor:
80
+ dense = dense_window_weight * dense_window + (1 - dense_window_weight) * dense_full
81
+ maxsim = maxsim_window if maxsim_window_weight == 1 else maxsim_window_weight * maxsim_window + (1 - maxsim_window_weight) * maxsim_full
82
+ fused = dense_weight * dense + (1 - dense_weight) * maxsim
83
+ if dense_only_max_tokens is None:
84
+ return fused
85
+ if document_tokens is None:
86
+ raise ValueError("dense_only_max_tokens needs document_tokens")
87
+ short = torch.as_tensor(document_tokens, device=fused.device) <= dense_only_max_tokens
88
+ return torch.where(short[None, :], dense, fused)
89
+
90
+
91
+ class Hyper3EmbedConfig(PretrainedConfig):
92
+
93
+ model_type = "hyper3_embed"
94
+
95
+ def __init__(self, backbone_subfolder: str = "backbone", embedding_dim: int = 1536, max_length: int = 4096,
96
+ embedding_config: dict[str, Any] | None = None, prompt_config: dict[str, Any] | None = None,
97
+ **kwargs: Any) -> None:
98
+ self.backbone_subfolder = backbone_subfolder
99
+ self.embedding_dim = embedding_dim
100
+ self.max_length = max_length
101
+ self.embedding_config = embedding_config if embedding_config is not None else {}
102
+ self.prompt_config = prompt_config if prompt_config is not None else {}
103
+ super().__init__(**kwargs)
104
+
105
+
106
+ class _GEGLU(nn.Module):
107
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
108
+ values, gates = x.chunk(2, dim=-1)
109
+ return values * F.gelu(gates)
110
+
111
+
112
+ class Hyper3EmbedLatentPooler(nn.Module):
113
+
114
+ def __init__(self, hidden_size: int, latent_count: int, num_heads: int, head_dim: int, ffn_mult: int, output_normalize: bool) -> None:
115
+ super().__init__()
116
+ self.num_heads, self.head_dim, self.latent_count = num_heads, head_dim, latent_count
117
+ self.inner_dim = num_heads * head_dim
118
+ self.output_normalize = output_normalize
119
+ self.latents = nn.Parameter(torch.zeros(latent_count, hidden_size))
120
+ self.token_norm = nn.LayerNorm(hidden_size)
121
+ self.latent_norm = nn.LayerNorm(hidden_size)
122
+ self.to_q = nn.Linear(hidden_size, self.inner_dim, bias=False)
123
+ self.to_kv = nn.Linear(hidden_size, self.inner_dim * 2, bias=False)
124
+ self.to_out = nn.Linear(self.inner_dim, hidden_size, bias=False)
125
+ self.ffn_norm = nn.LayerNorm(hidden_size)
126
+ self.ffn = nn.Sequential(nn.Linear(hidden_size, hidden_size * ffn_mult * 2), _GEGLU(), nn.Linear(hidden_size * ffn_mult, hidden_size))
127
+
128
+ def forward(self, hidden_states: torch.Tensor, pooling_mask: torch.Tensor) -> torch.Tensor:
129
+ hidden_states = self.refine(hidden_states)
130
+ mask = pooling_mask.unsqueeze(-1).to(hidden_states.dtype)
131
+ pooled = (hidden_states * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
132
+ return F.normalize(pooled, p=2, dim=-1) if self.output_normalize else pooled
133
+
134
+ def refine(self, hidden_states: torch.Tensor) -> torch.Tensor:
135
+ hidden_states = hidden_states.float()
136
+ batch, length, _ = hidden_states.shape
137
+ latents = self.latents.unsqueeze(0).expand(batch, -1, -1).float()
138
+ query = self.to_q(self.token_norm(hidden_states))
139
+ key, value = self.to_kv(self.latent_norm(latents)).chunk(2, dim=-1)
140
+ query = query.view(batch, length, self.num_heads, self.head_dim).transpose(1, 2)
141
+ key = key.view(batch, self.latent_count, self.num_heads, self.head_dim).transpose(1, 2)
142
+ value = value.view(batch, self.latent_count, self.num_heads, self.head_dim).transpose(1, 2)
143
+ attended = F.scaled_dot_product_attention(query, key, value).transpose(1, 2).reshape(batch, length, self.inner_dim)
144
+ hidden_states = hidden_states + self.to_out(attended)
145
+ return hidden_states + self.ffn(self.ffn_norm(hidden_states))
146
+
147
+
148
+ def named_prompts(prompt_config: dict[str, Any]) -> dict[str, str]:
149
+ types = prompt_config["type_prompts"]
150
+ template = prompt_config["instruction_template"]
151
+ named = {"query": types["retrieval"]["query"], "document": types["retrieval"]["positive"]}
152
+ named.update({family: sides["query"] for family, sides in types.items() if family != "retrieval"})
153
+ named.update({task: template.format(instruction=instruction) for task, instruction in prompt_config["task_instructions"].items()})
154
+ return named
155
+
156
+
157
+ def _resolve(path_or_id: str | os.PathLike, revision: str | None = None, token: bool | str | None = None,
158
+ cache_dir: str | None = None, local_files_only: bool = False) -> Path:
159
+ root = Path(path_or_id)
160
+ if root.is_dir():
161
+ return root
162
+ from huggingface_hub import snapshot_download
163
+
164
+ return Path(snapshot_download(str(path_or_id), revision=revision, token=token, cache_dir=cache_dir, local_files_only=local_files_only))
165
+
166
+
167
+ class Hyper3EmbedModel(PreTrainedModel):
168
+
169
+ config_class = Hyper3EmbedConfig
170
+ base_model_prefix = "hyper3_embed"
171
+ chunk_mix_scores = staticmethod(chunk_mix_scores)
172
+ maxsim_scores = staticmethod(maxsim_scores)
173
+ best_per_document = staticmethod(best_per_document)
174
+ fuse_scores = staticmethod(fuse_scores)
175
+
176
+ def __init__(self, config: Hyper3EmbedConfig) -> None:
177
+ super().__init__(config)
178
+ self.backbone: nn.Module | None = None
179
+ self.pooler: Hyper3EmbedLatentPooler | None = None
180
+
181
+ @classmethod
182
+ def from_pretrained(cls, pretrained_model_name_or_path: str | os.PathLike, *model_args: Any, config: Hyper3EmbedConfig | None = None,
183
+ revision: str | None = None, token: bool | str | None = None, cache_dir: str | None = None,
184
+ local_files_only: bool = False, dtype: torch.dtype | str | None = None, device: str | torch.device | None = None,
185
+ **kwargs: Any) -> Hyper3EmbedModel:
186
+ from safetensors.torch import load_file
187
+
188
+ unsupported = sorted(set(kwargs) & {"device_map", "quantization_config", "load_in_4bit", "load_in_8bit"})
189
+ if unsupported:
190
+ raise ValueError(
191
+ "This loader does not support " + ", ".join(unsupported)
192
+ + ". Load on one device with .to(device) or the explicit device argument."
193
+ )
194
+ dtype = kwargs.pop("torch_dtype", None) if dtype is None else dtype
195
+ if isinstance(dtype, str) and dtype != "auto":
196
+ dtype = getattr(torch, dtype)
197
+ if dtype in (None, "auto"):
198
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
199
+ root = _resolve(pretrained_model_name_or_path, revision, token, cache_dir, local_files_only)
200
+ missing = [name for name in RELEASE_FILES if not (root / name).is_file()]
201
+ if missing:
202
+ raise FileNotFoundError(f"{root} is not a Hyper3 Embed release directory (missing {missing})")
203
+ if config is None:
204
+ config = Hyper3EmbedConfig.from_pretrained(root)
205
+ if not isinstance(config.embedding_config, dict) or not config.embedding_config:
206
+ raise ValueError("config.json must contain embedding_config")
207
+ if not isinstance(config.prompt_config, dict) or not config.prompt_config:
208
+ raise ValueError("config.json must contain prompt_config")
209
+ model = cls(config)
210
+ settings = config.embedding_config
211
+ if settings["pooling"] != "latent_cross_attention_mean" or settings["attention_mode"] != "bidirectional":
212
+ raise ValueError(f"Unsupported Hyper3 Embed configuration in {root}")
213
+ if settings.get("projection_enabled", True) or settings.get("text_transform", "none") != "none":
214
+ raise ValueError("Unsupported Hyper3 Embed configuration: projection head or text transform")
215
+
216
+ backbone_dir = root / config.backbone_subfolder
217
+ backbone_config = AutoConfig.from_pretrained(backbone_dir)
218
+ model.tokenizer = AutoTokenizer.from_pretrained(root, config=backbone_config)
219
+ if model.tokenizer.pad_token is None:
220
+ model.tokenizer.pad_token = model.tokenizer.eos_token
221
+ model.tokenizer.padding_side = "right"
222
+ model.tokenizer.truncation_side = "right"
223
+ model.append_eos = bool(settings.get("append_eos", True))
224
+
225
+ text_config = backbone_config.get_text_config() if hasattr(backbone_config, "get_text_config") else backbone_config
226
+ saved = json.loads((backbone_dir / "config.json").read_text(encoding="utf-8"))
227
+ saved = saved.get("text_config", saved)
228
+ if saved.get("use_bidirectional_attention") == "all" and isinstance(saved.get("sliding_window"), int):
229
+ text_config.sliding_window = saved["sliding_window"]
230
+ text_config.is_causal = False
231
+ load_kwargs: dict[str, Any] = {"dtype": dtype}
232
+ if (torch.device(device).type == "cuda") if device is not None else torch.cuda.is_available():
233
+ load_kwargs["attn_implementation"] = "sdpa"
234
+ model.backbone = AutoModel.from_pretrained(backbone_dir, config=backbone_config, **load_kwargs)
235
+ for module in model.backbone.modules():
236
+ if hasattr(module, "is_causal"):
237
+ module.is_causal = False
238
+ if hasattr(model.backbone.config, "use_cache"):
239
+ model.backbone.config.use_cache = False
240
+
241
+ model.pooler = Hyper3EmbedLatentPooler(
242
+ int(settings["hidden_size"]),
243
+ latent_count=int(settings["latent_count"]),
244
+ num_heads=int(settings["latent_num_heads"]),
245
+ head_dim=int(settings["latent_head_dim"]),
246
+ ffn_mult=int(settings["latent_ffn_mult"]),
247
+ output_normalize=bool(settings["latent_output_normalize"]),
248
+ )
249
+ model.pooler.load_state_dict(load_file(str(root / "pooler.safetensors")))
250
+ model.pooler.float()
251
+ model.multivec = None
252
+ if int(settings.get("multivec_dim", 0)) > 0:
253
+ model.multivec = nn.Linear(int(settings["hidden_size"]), int(settings["multivec_dim"]), bias=False)
254
+ model.multivec.load_state_dict(load_file(str(root / "multivec_projection.safetensors")))
255
+ model.multivec.float()
256
+ model.eval()
257
+ if device is not None:
258
+ model.to(device)
259
+ return model
260
+
261
+ @property
262
+ def embedding_dim(self) -> int:
263
+ return self.pooler.to_out.out_features
264
+
265
+ def prompts(self) -> dict[str, str]:
266
+ return named_prompts(self.config.prompt_config)
267
+
268
+ def tokenize(self, texts: list[str], prompt: str = "", max_length: int | None = None) -> dict[str, torch.Tensor]:
269
+ prompt = prompt or ""
270
+ eos = self.tokenizer.eos_token
271
+ prepared = []
272
+ for text in texts:
273
+ value = prompt + text.strip()
274
+ if self.append_eos and eos and not value.endswith(eos):
275
+ value += eos
276
+ prepared.append(value)
277
+ batch = self.tokenizer(prepared, padding=True, truncation=True, max_length=max_length or self.config.max_length,
278
+ return_tensors="pt", return_offsets_mapping=True)
279
+ offsets = batch.pop("offset_mapping")
280
+ pooling_mask = batch["attention_mask"].clone()
281
+ if prompt:
282
+ pooling_mask[(offsets[..., 1] > offsets[..., 0]) & (offsets[..., 1] <= len(prompt))] = 0
283
+ return {"input_ids": batch["input_ids"], "attention_mask": batch["attention_mask"], "pooling_mask": pooling_mask}
284
+
285
+ def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, pooling_mask: torch.Tensor | None = None, **kwargs: Any) -> torch.Tensor:
286
+ hidden = self.backbone(input_ids=input_ids, attention_mask=attention_mask, return_dict=True).last_hidden_state
287
+ pooled = self.pooler(hidden, attention_mask if pooling_mask is None else pooling_mask)
288
+ return F.normalize(pooled.float(), p=2, dim=-1)
289
+
290
+ @torch.no_grad()
291
+ def encode(self, texts: str | list[str], prompt: str | None = None, prompt_name: str | None = None,
292
+ batch_size: int = 8, max_length: int | None = None) -> torch.Tensor:
293
+ if prompt is not None and prompt_name is not None:
294
+ raise ValueError("Pass prompt or prompt_name, not both")
295
+ if prompt_name is not None:
296
+ prompt = self.prompts()[prompt_name]
297
+ texts = [texts] if isinstance(texts, str) else list(texts)
298
+ device = next(self.backbone.parameters()).device
299
+ order = sorted(range(len(texts)), key=lambda index: len(texts[index]), reverse=True)
300
+ out = torch.empty((len(texts), self.embedding_dim), dtype=torch.float32)
301
+ for start in range(0, len(order), batch_size):
302
+ chunk = order[start : start + batch_size]
303
+ batch = {key: value.to(device) for key, value in self.tokenize([texts[index] for index in chunk], prompt or "", max_length).items()}
304
+ out[chunk] = self(**batch).cpu()
305
+ return out
306
+
307
+ def document_windows(self, texts: list[str], window: int = CHUNK_WINDOW, stride: int = CHUNK_STRIDE) -> tuple[list[str], list[int]]:
308
+ windows, owner, _ = self._windows(texts, window, stride)
309
+ return windows, owner
310
+
311
+ def _windows(self, texts: list[str], window: int, stride: int) -> tuple[list[str], list[int], list[int]]:
312
+ windows, owner, lengths = [], [], []
313
+ for index, text in enumerate(texts):
314
+ ids = self.tokenizer(text, add_special_tokens=False)["input_ids"]
315
+ starts = range(0, max(1, len(ids) - stride), stride)
316
+ windows += [self.tokenizer.decode(ids[start : start + window]) for start in starts]
317
+ owner += [index] * len(starts)
318
+ lengths.append(len(ids))
319
+ return windows, owner, lengths
320
+
321
+ def encode_windows(self, texts: str | list[str], prompt: str = "", batch_size: int = 8, window: int = CHUNK_WINDOW,
322
+ stride: int = CHUNK_STRIDE) -> tuple[torch.Tensor, torch.Tensor]:
323
+ texts = [texts] if isinstance(texts, str) else list(texts)
324
+ windows, owner = self.document_windows(texts, window, stride)
325
+ embeddings = self.encode(windows, prompt=prompt, batch_size=batch_size, max_length=window + 64)
326
+ return embeddings, torch.tensor(owner, dtype=torch.long)
327
+
328
+ @torch.no_grad()
329
+ def encode_with_tokens(self, texts: str | list[str], prompt: str | None = None, prompt_name: str | None = None,
330
+ batch_size: int = 8, max_length: int | None = None) -> tuple[torch.Tensor, list[torch.Tensor]]:
331
+ if self.multivec is None:
332
+ raise ValueError("this checkpoint has no MaxSim head")
333
+ if prompt is not None and prompt_name is not None:
334
+ raise ValueError("Pass prompt or prompt_name, not both")
335
+ if prompt_name is not None:
336
+ prompt = self.prompts()[prompt_name]
337
+ texts = [texts] if isinstance(texts, str) else list(texts)
338
+ device = next(self.backbone.parameters()).device
339
+ order = sorted(range(len(texts)), key=lambda index: len(texts[index]), reverse=True)
340
+ dense = torch.empty((len(texts), self.embedding_dim), dtype=torch.float32)
341
+ tokens: list[torch.Tensor] = [None] * len(texts)
342
+ for start in range(0, len(order), batch_size):
343
+ chunk = order[start : start + batch_size]
344
+ batch = {key: value.to(device) for key, value in self.tokenize([texts[index] for index in chunk], prompt or "", max_length).items()}
345
+ hidden = self.backbone(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], return_dict=True).last_hidden_state
346
+ refined = self.pooler.refine(hidden)
347
+ mask = batch["pooling_mask"].unsqueeze(-1).to(refined.dtype)
348
+ pooled = (refined * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
349
+ if self.pooler.output_normalize:
350
+ pooled = F.normalize(pooled, p=2, dim=-1)
351
+ dense[chunk] = F.normalize(pooled.float(), p=2, dim=-1).cpu()
352
+ vectors = F.normalize(self.multivec(refined.float()), p=2, dim=-1)
353
+ for row, index in enumerate(chunk):
354
+ tokens[index] = vectors[row][batch["pooling_mask"][row].bool()].half().cpu()
355
+ return dense, tokens
356
+
357
+ @torch.no_grad()
358
+ def multivector_parts(self, queries: list[str], documents: list[str], query_prompt: str | None = None,
359
+ document_prompt: str = "", batch_size: int = 8, window_block: int = 4096,
360
+ full_maxsim: bool | None = None) -> dict[str, torch.Tensor]:
361
+ query_prompt = self.prompts()["query"] if query_prompt is None else query_prompt
362
+ qd, qt = self.encode_with_tokens(queries, prompt=query_prompt, batch_size=batch_size, max_length=FUSE_QUERY_MAX_LENGTH)
363
+ return self.document_parts(qd, qt, documents, document_prompt=document_prompt, batch_size=batch_size,
364
+ window_block=window_block, full_maxsim=full_maxsim)
365
+
366
+ @torch.no_grad()
367
+ def document_parts(self, query_dense: torch.Tensor, query_tokens: list[torch.Tensor], documents: list[str],
368
+ document_prompt: str = "", batch_size: int = 8, window_block: int = 4096,
369
+ full_maxsim: bool | None = None) -> dict[str, torch.Tensor]:
370
+ device = next(self.backbone.parameters()).device
371
+ full_maxsim = FUSE_MAXSIM_WINDOW_WEIGHT != 1 if full_maxsim is None else full_maxsim
372
+ qd, qt = query_dense.to(device), [t.to(device) for t in query_tokens]
373
+ parts = {"dense_full": torch.empty(len(qt), len(documents), device=device),
374
+ "maxsim_full": torch.empty(len(qt), len(documents), device=device) if full_maxsim else None}
375
+ for start in range(0, len(documents), window_block // 8):
376
+ block = documents[start : start + window_block // 8]
377
+ dd, dt = (self.encode_with_tokens(block, prompt=document_prompt, batch_size=batch_size) if full_maxsim
378
+ else (self.encode(block, prompt=document_prompt, batch_size=batch_size), None))
379
+ parts["dense_full"][:, start : start + len(block)] = qd @ dd.to(device).T
380
+ if full_maxsim:
381
+ parts["maxsim_full"][:, start : start + len(block)] = maxsim_scores(qt, dt)
382
+ windows, owner, lengths = self._windows(documents, CHUNK_WINDOW, CHUNK_STRIDE)
383
+ parts["document_tokens"] = torch.tensor(lengths, dtype=torch.long, device=device)
384
+ owner = torch.tensor(owner, dtype=torch.long, device=device)
385
+ dense_best = torch.full((len(qt), len(documents)), -torch.inf, device=device)
386
+ maxsim_best = torch.full((len(qt), len(documents)), -torch.inf, device=device)
387
+ for start in range(0, len(windows), window_block):
388
+ wd, wt = self.encode_with_tokens(windows[start : start + window_block], prompt=document_prompt,
389
+ batch_size=batch_size, max_length=CHUNK_WINDOW + 64)
390
+ own = owner[start : start + window_block].expand(len(qt), -1)
391
+ dense_best = dense_best.scatter_reduce(1, own, qd @ wd.to(device).T, "amax")
392
+ maxsim_best = maxsim_best.scatter_reduce(1, own, maxsim_scores(qt, wt), "amax")
393
+ parts["dense_window"], parts["maxsim_window"] = dense_best, maxsim_best
394
+ return parts
395
+
396
+ def score_multivector(self, queries: list[str], documents: list[str], rerank_top_k: int | None = None,
397
+ fusion: dict[str, Any] | None = None, **kwargs: Any) -> torch.Tensor:
398
+ fusion = fusion or {}
399
+ if rerank_top_k is None:
400
+ return fuse_scores(**self.multivector_parts(queries, documents, **kwargs), **fusion)
401
+ kwargs = dict(kwargs)
402
+ query_prompt = kwargs.pop("query_prompt", None)
403
+ document_prompt, batch_size = kwargs.get("document_prompt", ""), kwargs.get("batch_size", 8)
404
+ q = self.encode(queries, prompt=self.prompts()["query"] if query_prompt is None else query_prompt, batch_size=batch_size,
405
+ max_length=FUSE_QUERY_MAX_LENGTH)
406
+ d = self.encode(documents, prompt=document_prompt, batch_size=batch_size)
407
+ w, owner = self.encode_windows(documents, prompt=document_prompt, batch_size=batch_size)
408
+ first = chunk_mix_scores(q, d, w, owner, weight=fusion.get("dense_window_weight", FUSE_DENSE_WINDOW_WEIGHT))
409
+ top = first.topk(min(rerank_top_k, len(documents)), dim=1).indices
410
+ candidates = sorted(set(top.flatten().tolist()))
411
+ sub = fuse_scores(**self.multivector_parts(queries, [documents[i] for i in candidates], query_prompt=query_prompt, **kwargs),
412
+ **fusion)
413
+ scores = torch.full_like(first, -torch.inf)
414
+ column = {doc: j for j, doc in enumerate(candidates)}
415
+ for row in range(len(queries)):
416
+ keep = top[row].tolist()
417
+ scores[row, keep] = sub[row, [column[i] for i in keep]].to(scores.device)
418
+ return scores
modules.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "hyper3_embed_sentence_transformers.Hyper3EmbedSentenceTransformer"
7
+ }
8
+ ]
multivec_projection.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70d4f1cc0bdc23d59ae643b136f2e44b7bf0e507e2ba6dc1d825d12ee7299789
3
+ size 786512
pooler.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41f5d2c62e0b7c4464f6bf75219e9807c1e270d1ca9ea4fb452899841ac426c9
3
+ size 139291824
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70e049b787674626d24cb68f3e26c2041ba862d95c30d84beec08f9da730dc46
3
+ size 32169879
tokenizer_config.json ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_token": "<|audio|>",
3
+ "backend": "tokenizers",
4
+ "boa_token": "<|audio>",
5
+ "boi_token": "<|image>",
6
+ "bos_token": "<bos>",
7
+ "eoa_token": "<audio|>",
8
+ "eoc_token": "<channel|>",
9
+ "eoi_token": "<image|>",
10
+ "eos_token": "<eos>",
11
+ "eot_token": "<turn|>",
12
+ "escape_token": "<|\"|>",
13
+ "etc_token": "<tool_call|>",
14
+ "etd_token": "<tool|>",
15
+ "etr_token": "<tool_response|>",
16
+ "extra_special_tokens": [
17
+ "<|video|>"
18
+ ],
19
+ "image_token": "<|image|>",
20
+ "is_local": true,
21
+ "local_files_only": true,
22
+ "mask_token": "<mask>",
23
+ "max_length": 512,
24
+ "model_max_length": 1000000000000000019884624838656,
25
+ "model_specific_special_tokens": {
26
+ "audio_token": "<|audio|>",
27
+ "boa_token": "<|audio>",
28
+ "boi_token": "<|image>",
29
+ "eoa_token": "<audio|>",
30
+ "eoc_token": "<channel|>",
31
+ "eoi_token": "<image|>",
32
+ "eot_token": "<turn|>",
33
+ "escape_token": "<|\"|>",
34
+ "etc_token": "<tool_call|>",
35
+ "etd_token": "<tool|>",
36
+ "etr_token": "<tool_response|>",
37
+ "image_token": "<|image|>",
38
+ "soc_token": "<|channel>",
39
+ "sot_token": "<|turn>",
40
+ "stc_token": "<|tool_call>",
41
+ "std_token": "<|tool>",
42
+ "str_token": "<|tool_response>",
43
+ "think_token": "<|think|>"
44
+ },
45
+ "pad_to_multiple_of": null,
46
+ "pad_token": "<pad>",
47
+ "pad_token_type_id": 0,
48
+ "padding_side": "right",
49
+ "processor_class": "Gemma4Processor",
50
+ "response_schema": {
51
+ "properties": {
52
+ "content": {
53
+ "type": "string"
54
+ },
55
+ "role": {
56
+ "const": "assistant"
57
+ },
58
+ "thinking": {
59
+ "type": "string"
60
+ },
61
+ "tool_calls": {
62
+ "items": {
63
+ "properties": {
64
+ "function": {
65
+ "properties": {
66
+ "arguments": {
67
+ "additionalProperties": {},
68
+ "type": "object",
69
+ "x-parser": "gemma4-tool-call"
70
+ },
71
+ "name": {
72
+ "type": "string"
73
+ }
74
+ },
75
+ "type": "object",
76
+ "x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})"
77
+ },
78
+ "type": {
79
+ "const": "function"
80
+ }
81
+ },
82
+ "type": "object"
83
+ },
84
+ "type": "array",
85
+ "x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>"
86
+ }
87
+ },
88
+ "type": "object",
89
+ "x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?"
90
+ },
91
+ "response_template": {
92
+ "defaults": {
93
+ "role": "assistant"
94
+ },
95
+ "fields": {
96
+ "content": {
97
+ "close": [
98
+ "<turn|>",
99
+ "<|tool_response>",
100
+ "<eos>"
101
+ ],
102
+ "content": "text"
103
+ },
104
+ "thinking": {
105
+ "close": "<channel|>",
106
+ "content": "text",
107
+ "open": "<|channel>thought\n"
108
+ },
109
+ "tool_calls": {
110
+ "close": "<tool_call|>",
111
+ "content": "json",
112
+ "content_args": {
113
+ "string_delims": [
114
+ [
115
+ "<|\"|>",
116
+ "<|\"|>"
117
+ ]
118
+ ],
119
+ "unquoted_keys": true
120
+ },
121
+ "open_pattern": "<\\|tool_call>call:(?P<name>\\w+)",
122
+ "repeats": true,
123
+ "transform": {
124
+ "function": {
125
+ "arguments": "{content}",
126
+ "name": "{name}"
127
+ },
128
+ "type": "function"
129
+ }
130
+ }
131
+ },
132
+ "start_anchor": [
133
+ "<|turn>model\n",
134
+ "<tool_response|>"
135
+ ]
136
+ },
137
+ "soc_token": "<|channel>",
138
+ "sot_token": "<|turn>",
139
+ "stc_token": "<|tool_call>",
140
+ "std_token": "<|tool>",
141
+ "str_token": "<|tool_response>",
142
+ "stride": 0,
143
+ "think_token": "<|think|>",
144
+ "tokenizer_class": "GemmaTokenizer",
145
+ "truncation_side": "right",
146
+ "truncation_strategy": "longest_first",
147
+ "unk_token": "<unk>"
148
+ }