tomkay commited on
Commit
4e8aac7
·
verified ·
1 Parent(s): f0fc3cd

Add baa.ai Embedding-Reranker-Arctic-L-RerankerV2M3-v1 (unified shared word-emb)

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
+ embedder/tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ reranker/tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ baa.ai · Embedding-Reranker-Arctic-L-RerankerV2M3-v1
2
+ Copyright (c) 2026 baa.ai
3
+
4
+ This product is a derivative work licensed under the Apache License, Version 2.0.
5
+ It re-packages and modifies the following upstream models:
6
+
7
+ 1. Snowflake/snowflake-arctic-embed-l-v2.0 (license: Apache-2.0)
8
+ Used as the bi-encoder embedder. Provides the canonical (shared)
9
+ word-embedding table for the combined model.
10
+ https://huggingface.co/Snowflake/snowflake-arctic-embed-l-v2.0
11
+
12
+ 2. BAAI/bge-reranker-v2-m3 (license: Apache-2.0)
13
+ Used as the cross-encoder reranker. Its word-embedding table has been
14
+ removed on disk and is injected at load time from the shared table
15
+ above, reducing the combined footprint.
16
+ https://huggingface.co/BAAI/bge-reranker-v2-m3
17
+
18
+ Both upstream models derive from the XLM-RoBERTa-large architecture.
19
+
20
+ Modifications by baa.ai:
21
+ - Unified the two models into a single artifact over one shared
22
+ word-embedding table (the reranker's word-embedding matrix is stored
23
+ once, in the embedder, and injected at load).
24
+ - Added a combined loader (modeling_baa.py) exposing embed() and rerank().
25
+
26
+ This NOTICE file is provided in accordance with Section 4(d) of the
27
+ Apache License, Version 2.0. See the LICENSE file for the full license text.
README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: sentence-transformers
4
+ tags:
5
+ - retrieval
6
+ - embeddings
7
+ - reranker
8
+ - cross-encoder
9
+ - rag
10
+ - sentence-similarity
11
+ pipeline_tag: sentence-similarity
12
+ ---
13
+
14
+ # baa.ai · Embedding-Reranker-Arctic-L-RerankerV2M3-v1
15
+
16
+ **A single model that does both halves of RAG retrieval — bi-encoder embedding *and* cross-encoder reranking — over one shared word-embedding table.**
17
+
18
+ The embedder and reranker share their word-embedding table (stored once), so the packaged model is **~22.5% smaller on disk than shipping the two components separately**, with **no measured loss in retrieval quality**.
19
+
20
+ ## Why this model
21
+
22
+ Most RAG stacks bolt an embedder onto a reranker and pay for both. A well-matched embedder + reranker that share a backbone recover the right documents just as well — in a single, smaller download.
23
+
24
+ - **Two jobs, one download** — embed for retrieval, then rerank the candidates.
25
+ - **Smaller footprint** — the shared word-embedding table is stored once.
26
+ - **Strong default** — a sensible starting point for production RAG.
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ from modeling_baa import BaaEmbeddingReranker # included in this repo
32
+
33
+ m = BaaEmbeddingReranker("baa-ai/Embedding-Reranker-Arctic-L-RerankerV2M3-v1")
34
+ qv = m.embed(["how does a cross-encoder reranker work?"], is_query=True)[0]
35
+ dv = m.embed(["a cross-encoder scores a (query, document) pair jointly",
36
+ "bi-encoders embed query and document separately for fast retrieval"])
37
+ ranked = m.rerank("how does a cross-encoder reranker work?",
38
+ ["a cross-encoder scores a (query, document) pair jointly",
39
+ "the mitochondria is the powerhouse of the cell"])
40
+ # -> [(doc, score), ...] sorted best-first
41
+ ```
42
+
43
+ ## Get the optimal models for *your* data
44
+
45
+ This model is a great **default**. But the best embedder and reranker are **corpus-specific**. **baa.ai offers exclusive tooling that identifies the optimal embedding and reranking models for your specific data** — if you want that tailored recommendation, **reach out to baa.ai**.
46
+
47
+ ## Specs
48
+
49
+ | | |
50
+ |---|---|
51
+ | Embedding dim | 1024 |
52
+ | Vocab | 250002 |
53
+ | Max sequence length | 512 |
54
+ | Combined params | ~879.5M (vs ~1135.5M separate) |
55
+ | Footprint vs separate models | ~22.5% smaller on disk, no measured quality loss |
56
+ | Hardware | CPU / edge / GPU |
57
+
58
+ ## License & attribution
59
+
60
+ Released under the **Apache License 2.0**. Derivative work re-packaging two upstream models into a single shared-backbone artifact (see `NOTICE`):
61
+ - `Snowflake/snowflake-arctic-embed-l-v2.0` (embedder)
62
+ - `BAAI/bge-reranker-v2-m3` (reranker)
63
+
64
+ © baa.ai. Provided "as is" without warranty; see `LICENSE`.
config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "baa-embed-rerank",
3
+ "description": "Unified bi-encoder embedder + cross-encoder reranker sharing one word-embedding table.",
4
+ "components": {
5
+ "embedder": "embedder/",
6
+ "reranker": "reranker/"
7
+ },
8
+ "loader": "modeling_baa.BaaEmbeddingReranker",
9
+ "embed_query_prompt": "query: ",
10
+ "embed_doc_prompt": "",
11
+ "embedding_dim": 1024,
12
+ "vocab_size": 250002,
13
+ "max_seq_length": 512,
14
+ "separate_params_millions": 1135.5,
15
+ "combined_params_millions": 879.5,
16
+ "disk_saving_pct": 22.5,
17
+ "license": "apache-2.0",
18
+ "trust_remote_code": true,
19
+ "upstream": {
20
+ "embedder": "Snowflake/snowflake-arctic-embed-l-v2.0",
21
+ "reranker": "BAAI/bge-reranker-v2-m3"
22
+ }
23
+ }
embedder/1_Pooling/config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "embedding_dimension": 1024,
3
+ "pooling_mode": "cls",
4
+ "include_prompt": true
5
+ }
embedder/README.md ADDED
The diff for this file is too large to render. See raw diff
 
embedder/config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "XLMRobertaModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 1024,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 4096,
16
+ "is_decoder": false,
17
+ "layer_norm_eps": 1e-05,
18
+ "matryoshka_dimensions": [
19
+ 256
20
+ ],
21
+ "max_position_embeddings": 8194,
22
+ "model_type": "xlm-roberta",
23
+ "num_attention_heads": 16,
24
+ "num_hidden_layers": 24,
25
+ "output_past": true,
26
+ "pad_token_id": 1,
27
+ "position_embedding_type": "absolute",
28
+ "tie_word_embeddings": true,
29
+ "transformers_version": "5.12.1",
30
+ "type_vocab_size": 1,
31
+ "use_cache": true,
32
+ "vocab_size": 250002
33
+ }
embedder/config_sentence_transformers.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "pytorch": "2.12.1",
4
+ "sentence_transformers": "5.6.0",
5
+ "transformers": "5.12.1"
6
+ },
7
+ "default_prompt_name": null,
8
+ "model_type": "SentenceTransformer",
9
+ "prompts": {
10
+ "document": "",
11
+ "query": "query: "
12
+ },
13
+ "similarity_fn_name": "cosine"
14
+ }
embedder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21bf1a120b1c6562aeec379dfa9039b0d360591c784cb1c6786e87256b738ee1
3
+ size 2271064456
embedder/modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.base.modules.transformer.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.sentence_transformer.modules.pooling.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.sentence_transformer.modules.normalize.Normalize"
19
+ }
20
+ ]
embedder/sentence_bert_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transformer_task": "feature-extraction",
3
+ "modality_config": {
4
+ "text": {
5
+ "method": "forward",
6
+ "method_output_name": "last_hidden_state"
7
+ }
8
+ },
9
+ "module_output_name": "token_embeddings"
10
+ }
embedder/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:883b037111086fd4dfebbbc9b7cee11e1517b5e0c0514879478661440f137085
3
+ size 17082987
embedder/tokenizer_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": true,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<s>",
5
+ "clean_up_tokenization_spaces": true,
6
+ "cls_token": "<s>",
7
+ "eos_token": "</s>",
8
+ "is_local": false,
9
+ "local_files_only": false,
10
+ "mask_token": "<mask>",
11
+ "max_length": 512,
12
+ "model_max_length": 8192,
13
+ "pad_to_multiple_of": null,
14
+ "pad_token": "<pad>",
15
+ "pad_token_type_id": 0,
16
+ "padding_side": "right",
17
+ "sep_token": "</s>",
18
+ "stride": 0,
19
+ "tokenizer_class": "XLMRobertaTokenizer",
20
+ "truncation_side": "right",
21
+ "truncation_strategy": "longest_first",
22
+ "unk_token": "<unk>"
23
+ }
modeling_baa.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """baa.ai unified Embedding+Reranker loader (generic).
2
+
3
+ A single artifact that does both halves of RAG retrieval — bi-encoder embedding AND cross-encoder reranking —
4
+ over ONE shared word-embedding table. The reranker's word-embedding matrix is stored only once (in the
5
+ embedder) and injected at load, so the packaged model is smaller than shipping the two components separately,
6
+ at no measured quality cost.
7
+
8
+ Works for BERT-based and XLM-RoBERTa-based stacks alike: the reranker's encoder submodule is resolved
9
+ generically via `reranker.base_model` (so `.bert` / `.roberta` are both handled). Optional per-model query/doc
10
+ prompts are read from config.json (e.g. arctic uses "query: ").
11
+
12
+ Usage:
13
+ from modeling_baa import BaaEmbeddingReranker
14
+ m = BaaEmbeddingReranker("path/to/model-dir")
15
+ qv = m.embed(["what is a cross-encoder?"], is_query=True) # normalized bi-encoder vectors
16
+ dv = m.embed(["a cross-encoder scores a (query, doc) pair jointly"])
17
+ ranked = m.rerank("what is a cross-encoder?", ["doc A ...", "doc B ..."]) # [(doc, score), ...] desc
18
+ """
19
+ import os, json, torch
20
+ from safetensors.torch import load_file
21
+ from sentence_transformers import SentenceTransformer
22
+ from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer
23
+
24
+
25
+ class BaaEmbeddingReranker:
26
+ def __init__(self, path=None, device=None):
27
+ path = path or os.path.dirname(os.path.abspath(__file__))
28
+ self.device = device or ("mps" if torch.backends.mps.is_available()
29
+ else ("cuda" if torch.cuda.is_available() else "cpu"))
30
+ cfg = {}
31
+ cfg_path = os.path.join(path, "config.json")
32
+ if os.path.exists(cfg_path):
33
+ cfg = json.load(open(cfg_path))
34
+ self.q_prompt = cfg.get("embed_query_prompt", "") or ""
35
+ self.d_prompt = cfg.get("embed_doc_prompt", "") or ""
36
+ trc = bool(cfg.get("trust_remote_code", False))
37
+ emb_dir, rr_dir = os.path.join(path, "embedder"), os.path.join(path, "reranker")
38
+
39
+ # embedder = bi-encoder; holds the canonical shared word-embedding table
40
+ self.embedder = SentenceTransformer(emb_dir, device=self.device, trust_remote_code=trc)
41
+ shared_wemb = self.embedder[0].auto_model.embeddings.word_embeddings.weight.data
42
+
43
+ # reranker = cross-encoder seq-classifier; word-embedding stripped on disk -> injected from shared table
44
+ rr_cfg = AutoConfig.from_pretrained(rr_dir, trust_remote_code=trc)
45
+ self.reranker = AutoModelForSequenceClassification.from_config(rr_cfg, trust_remote_code=trc)
46
+ self.reranker.load_state_dict(load_file(os.path.join(rr_dir, "model.safetensors")), strict=False)
47
+ # resolve the encoder submodule generically (.bert for BERT, .roberta for XLM-R, ...)
48
+ base = self.reranker.base_model
49
+ base.embeddings.word_embeddings.weight.data = shared_wemb.to(self.reranker.dtype).clone()
50
+ self.reranker.to(self.device).eval()
51
+ self.rr_tok = AutoTokenizer.from_pretrained(rr_dir, trust_remote_code=trc)
52
+
53
+ def embed(self, texts, is_query=False, batch_size=32):
54
+ """Return L2-normalized bi-encoder vectors. Applies the model's query/doc prompt if configured."""
55
+ prompt = self.q_prompt if is_query else self.d_prompt
56
+ texts = [prompt + t for t in texts] if prompt else list(texts)
57
+ return self.embedder.encode(texts, normalize_embeddings=True,
58
+ batch_size=batch_size, show_progress_bar=False)
59
+
60
+ @torch.no_grad()
61
+ def rerank(self, query, docs, top_k=None, batch_size=32):
62
+ """Cross-encoder relevance scores for (query, doc) pairs; returns [(doc, score), ...] sorted desc."""
63
+ scores = []
64
+ for i in range(0, len(docs), batch_size):
65
+ enc = self.rr_tok([(query, d[:2000]) for d in docs[i:i + batch_size]], padding=True,
66
+ truncation=True, max_length=512, return_tensors="pt").to(self.device)
67
+ scores.extend(self.reranker(**enc).logits[:, 0].float().cpu().tolist())
68
+ order = sorted(range(len(docs)), key=lambda j: -scores[j])
69
+ if top_k:
70
+ order = order[:top_k]
71
+ return [(docs[j], scores[j]) for j in order]
72
+
73
+
74
+ if __name__ == "__main__":
75
+ import numpy as np
76
+ m = BaaEmbeddingReranker()
77
+ q = "How does a cross-encoder reranker work?"
78
+ docs = ["A cross-encoder jointly encodes the query and document to score relevance.",
79
+ "The mitochondria is the powerhouse of the cell.",
80
+ "Bi-encoders embed query and document separately for fast retrieval."]
81
+ qv = m.embed([q], is_query=True)[0]; dv = m.embed(docs)
82
+ print("embed cos:", [round(float(np.dot(qv, d)), 3) for d in dv])
83
+ print("rerank :", [(round(s, 2), d[:45]) for d, s in m.rerank(q, docs)])
reranker/config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "XLMRobertaForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 1024,
14
+ "id2label": {
15
+ "0": "LABEL_0"
16
+ },
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 4096,
19
+ "is_decoder": false,
20
+ "label2id": {
21
+ "LABEL_0": 0
22
+ },
23
+ "layer_norm_eps": 1e-05,
24
+ "max_position_embeddings": 8194,
25
+ "model_type": "xlm-roberta",
26
+ "num_attention_heads": 16,
27
+ "num_hidden_layers": 24,
28
+ "output_past": true,
29
+ "pad_token_id": 1,
30
+ "position_embedding_type": "absolute",
31
+ "tie_word_embeddings": true,
32
+ "transformers_version": "5.12.1",
33
+ "type_vocab_size": 1,
34
+ "use_cache": true,
35
+ "vocab_size": 250002
36
+ }
reranker/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1666adf94fd3e60bb127998660adac7591ebb8677d2e30bd1c18940e1a10477c
3
+ size 1247062844
reranker/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5df1f55d60c9705a501ab9a75550728625740741fe4be308dac4806c16b7d51d
3
+ size 17098085
reranker/tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": true,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<s>",
5
+ "clean_up_tokenization_spaces": true,
6
+ "cls_token": "<s>",
7
+ "eos_token": "</s>",
8
+ "is_local": false,
9
+ "local_files_only": false,
10
+ "mask_token": "<mask>",
11
+ "model_max_length": 8192,
12
+ "pad_token": "<pad>",
13
+ "sep_token": "</s>",
14
+ "sp_model_kwargs": {},
15
+ "tokenizer_class": "XLMRobertaTokenizer",
16
+ "unk_token": "<unk>"
17
+ }