TheoDB commited on
Commit
3ac36c5
·
verified ·
1 Parent(s): ce07143

Upload BidirLM-0.6B-Embedding

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
+ final_results.png filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 1024,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
README.md ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - mteb
4
+ - sentence-transformers
5
+ - transformers
6
+ - embedding
7
+ - bidirectional
8
+ - multilingual
9
+ pipeline_tag: sentence-similarity
10
+ license: apache-2.0
11
+ base_model: BidirLM/BidirLM-0.6B-Base
12
+ language:
13
+ - multilingual
14
+ - af
15
+ - am
16
+ - ar
17
+ - az
18
+ - be
19
+ - bg
20
+ - bn
21
+ - bs
22
+ - ca
23
+ - ceb
24
+ - cs
25
+ - cy
26
+ - da
27
+ - de
28
+ - el
29
+ - en
30
+ - es
31
+ - et
32
+ - eu
33
+ - fa
34
+ - fi
35
+ - fr
36
+ - ga
37
+ - gl
38
+ - gu
39
+ - ha
40
+ - he
41
+ - hi
42
+ - hr
43
+ - ht
44
+ - hu
45
+ - hy
46
+ - id
47
+ - ig
48
+ - is
49
+ - it
50
+ - ja
51
+ - jv
52
+ - ka
53
+ - kk
54
+ - kn
55
+ - ko
56
+ - ky
57
+ - lt
58
+ - lv
59
+ - mg
60
+ - mk
61
+ - ml
62
+ - mr
63
+ - ms
64
+ - mt
65
+ - my
66
+ - nb
67
+ - ne
68
+ - nl
69
+ - nso
70
+ - ny
71
+ - pa
72
+ - pl
73
+ - ps
74
+ - pt
75
+ - ro
76
+ - ru
77
+ - sd
78
+ - si
79
+ - sk
80
+ - sl
81
+ - sn
82
+ - so
83
+ - sq
84
+ - sr
85
+ - su
86
+ - sv
87
+ - sw
88
+ - ta
89
+ - te
90
+ - th
91
+ - tl
92
+ - tr
93
+ - uk
94
+ - ur
95
+ - vi
96
+ - wo
97
+ - xh
98
+ - yo
99
+ - zh
100
+ - zu
101
+ ---
102
+
103
+ # BidirLM-0.6B
104
+
105
+ BidirLM is a family of 5 frontier bidirectional encoders, including an omnimodal variant at 2.5B, adapted from causal decoder LLMs. Contrary to contrastive-only models, BidirLM relies on a prior masking phase (MNTP) that enables state-of-the-art results on task-specific fine-tuning (NER, classification, NLI) while achieving frontier performance on embedding benchmarks (MTEB) against open-source alternatives.
106
+
107
+ ![Multilingual model performance by size on XTREME-Benchmark Augmented and MTEB Multilingual V2](final_results.png)
108
+
109
+ | Model | Base LLM | Parameters | Embedding Dim | Max Tokens | MTEB Multi. V2 (Mean Task) |
110
+ |---|---|---|---|---|---|
111
+ | BidirLM-270M | Gemma3-270M | 268M | 640 | 512 | 55.5 |
112
+ | **BidirLM-0.6B** | **Qwen3-0.6B** | **596M** | **1024** | **512** (\*) | **59.6** |
113
+ | BidirLM-1B | Gemma3-1B | 1001M | 1152 | 512 | 62.1 |
114
+ | BidirLM-1.7B | Qwen3-1.7B | 1721M | 2048 | 512 | 62.9 |
115
+ | BidirLM-Omni-2.5B | Qwen3-1.7B | 2.5B | 2048 | 512 | 63.1 |
116
+
117
+ (\*) While evaluated on MTEB with a max length of 512, the underlying architecture supports up to 40,960 context length (Qwen3). Longer sequences can be used by adjusting `model.max_seq_length` in Sentence Transformers or `max_length` in the tokenizer.
118
+
119
+ ## Supported Tasks
120
+
121
+ **General embeddings** (via Sentence Transformers): retrieval, semantic similarity (STS), clustering, classification, pair classification, reranking, bitext mining, multilabel classification
122
+
123
+ **Downstream fine-tuning** (via Transformers): sequence classification (e.g. MNLI, XNLI, PAWS-X, MathShepherd), token classification (e.g. PAN-X, POS), information retrieval (e.g. MIRACL, CodeSearchNet), sequence regression (e.g. Seahorse)
124
+
125
+ ## Usage
126
+
127
+ ### Sentence Transformers
128
+
129
+ Use Sentence Transformers to compute embeddings for any text representation task.
130
+
131
+ ```python
132
+ from sentence_transformers import SentenceTransformer
133
+
134
+ model = SentenceTransformer("BidirLM/BidirLM-0.6B", trust_remote_code=True)
135
+
136
+ queries = [
137
+ "What is the capital of France?",
138
+ "How does photosynthesis work?",
139
+ ]
140
+ documents = [
141
+ "Paris is the capital and largest city of France, situated on the river Seine.",
142
+ "Photosynthesis is the process by which plants convert sunlight, water, and CO2 into glucose and oxygen.",
143
+ ]
144
+
145
+ query_embeddings = model.encode(queries)
146
+ document_embeddings = model.encode(documents)
147
+
148
+ similarities = model.similarity(query_embeddings, document_embeddings)
149
+ print(similarities)
150
+ ```
151
+
152
+ ### Fine-tuning for Downstream Tasks
153
+
154
+ BidirLM can be directly fine-tuned for downstream tasks:
155
+
156
+ ```python
157
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification
158
+
159
+ tokenizer = AutoTokenizer.from_pretrained("BidirLM/BidirLM-0.6B", trust_remote_code=True)
160
+
161
+ # Sequence classification (e.g., NLI: entailment, neutral, contradiction)
162
+ seq_model = AutoModelForSequenceClassification.from_pretrained(
163
+ "BidirLM/BidirLM-0.6B",
164
+ trust_remote_code=True,
165
+ num_labels=3,
166
+ )
167
+
168
+ # Token classification (e.g., NER)
169
+ tok_model = AutoModelForTokenClassification.from_pretrained(
170
+ "BidirLM/BidirLM-0.6B",
171
+ trust_remote_code=True,
172
+ num_labels=7,
173
+ )
174
+
175
+ # Fine-tune with HuggingFace Trainer
176
+ ```
177
+
178
+ ## Evaluation
179
+
180
+ Please follow the [mteb repository](https://github.com/embeddings-benchmark/mteb) on how to reproduce our scores. The evaluation prompts used for each task are also available at [mteb_v2_eval_prompts.json](mteb_v2_eval_prompts.json).
181
+
182
+ ## Supported Languages
183
+
184
+ Multilingual support across over 119 languages, inherited from the Qwen3 base model and reinforced through contrastive training with 87 languages.
185
+
186
+ ## Requirements
187
+
188
+ This model requires `trust_remote_code=True` as it uses a custom bidirectional architecture.
189
+
190
+ ```
191
+ transformers>=4.57.6,<5.0.0
192
+ sentence-transformers>=5.0.0
193
+ ```
194
+
195
+ ## FAQ
196
+
197
+ ### 1. What pooling strategy does this model use?
198
+
199
+ The model uses **mean pooling**. This is handled automatically when using Sentence Transformers.
200
+
201
+ ### 2. Do I need `trust_remote_code=True`?
202
+
203
+ Yes. BidirLM uses a custom bidirectional architecture (`BidirLMModel`) that requires loading custom code from the repository.
204
+
205
+ ### 3. Why are my reproduced results slightly different from those reported in the model card?
206
+
207
+ Different versions of `transformers` and `pytorch` could cause negligible but non-zero performance differences. This model was trained and evaluated with `transformers==4.57.6` and `pytorch==2.6.0`.
208
+
209
+ ### 4. What is the relationship between BidirLM-0.6B and BidirLM-0.6B-base?
210
+
211
+ [BidirLM/BidirLM-0.6B-Base](https://huggingface.co/BidirLM/BidirLM-0.6B-Base) is the intermediate MNTP-adapted checkpoint (bidirectional pretraining stage). BidirLM-0.6B is the final contrastive fine-tuned version optimized for both sentence embeddings and downstream fine-tuning.
212
+
213
+ ### 5. How is BidirLM different from other embedding models?
214
+
215
+ Most embedding models (BGE-M3, KaLM, EmbedGemma, Qwen3-Embedding) use contrastive-only training, which optimizes embeddings but sacrifices fine-tuning ability. BidirLM restores a prior MNTP phase, advancing the Pareto frontier on both MTEB and XTREME simultaneously.
216
+
217
+ ## Citation
218
+
219
+ ```bibtex
220
+ @misc{boizard2026bidirlmtextomnimodalbidirectional,
221
+ title={BidirLM: From Text to Omnimodal Bidirectional Encoders by Adapting and Composing Causal LLMs},
222
+ author={Nicolas Boizard and Théo Deschamps-Berger and Hippolyte Gisserot-Boukhlef and Céline Hudelot and Pierre Colombo},
223
+ year={2026},
224
+ eprint={2604.02045},
225
+ archivePrefix={arXiv},
226
+ primaryClass={cs.CL},
227
+ url={https://arxiv.org/abs/2604.02045},
228
+ }
229
+ ```
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|mask|>": 151663,
20
+ "<|object_ref_end|>": 151647,
21
+ "<|object_ref_start|>": 151646,
22
+ "<|quad_end|>": 151651,
23
+ "<|quad_start|>": 151650,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BidirLMModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_bidirlm.BidirLMConfig",
9
+ "AutoModel": "modeling_bidirlm.BidirLMModel",
10
+ "AutoModelForMaskedLM": "modeling_bidirlm.BidirLMForMaskedLM",
11
+ "AutoModelForPreTraining": "modeling_bidirlm.BidirLMPreTrainedModel",
12
+ "AutoModelForSequenceClassification": "modeling_bidirlm.BidirLMForSequenceClassification",
13
+ "AutoModelForTokenClassification": "modeling_bidirlm.BidirLMForTokenClassification"
14
+ },
15
+ "bos_token_id": 151644,
16
+ "clf_pooling": "late",
17
+ "dtype": "bfloat16",
18
+ "eos_token_id": 151645,
19
+ "head_dim": 128,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 1024,
22
+ "initializer_range": 0.02,
23
+ "intermediate_size": 3072,
24
+ "mask_token": "<|mask|>",
25
+ "mask_token_id": 151663,
26
+ "max_position_embeddings": 40960,
27
+ "model_type": "bidirlm",
28
+ "num_attention_heads": 16,
29
+ "num_hidden_layers": 28,
30
+ "num_key_value_heads": 8,
31
+ "pad_token_id": 151645,
32
+ "rms_norm_eps": 1e-06,
33
+ "rope_scaling": null,
34
+ "rope_theta": 1000000,
35
+ "tie_word_embeddings": true,
36
+ "transformers_version": "4.57.6",
37
+ "vocab_size": 151936
38
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "SentenceTransformer",
3
+ "__version__": {
4
+ "sentence_transformers": "5.2.3",
5
+ "transformers": "4.57.6",
6
+ "pytorch": "2.6.0"
7
+ },
8
+ "prompts": {
9
+ "query": "",
10
+ "document": ""
11
+ },
12
+ "default_prompt_name": null,
13
+ "similarity_fn_name": "cosine"
14
+ }
configuration_bidirlm.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BidirLM model configuration"""
16
+
17
+ import transformers
18
+ _v = transformers.__version__
19
+ if _v < "4.57.6" or _v >= "5.0.0":
20
+ raise ImportError(
21
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
22
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
23
+ )
24
+
25
+ from transformers.configuration_utils import PretrainedConfig
26
+ from transformers.modeling_rope_utils import rope_config_validation
27
+ from transformers.utils import logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class BidirLMConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`BidirLMModel`]. It is used to instantiate a
36
+ BidirLM model according to the specified arguments, defining the model architecture. Instantiating a configuration
37
+ with the defaults will yield a similar configuration to that of
38
+ Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B) WITH BIDIRECTIONAL ATTENTION MECHANISM.
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 151936):
43
+ Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Qwen3Model`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 22016):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*, defaults to 32):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details, check out [this
59
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
60
+ head_dim (`int`, *optional*, defaults to 128):
61
+ The attention head dimension.
62
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
63
+ The non-linear activation function (function or string) in the decoder.
64
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
65
+ The maximum sequence length that this model might ever be used with.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
71
+ Whether the model's input and output word embeddings should be tied.
72
+ rope_theta (`float`, *optional*, defaults to 10000.0):
73
+ The base period of the RoPE embeddings.
74
+ rope_scaling (`Dict`, *optional*):
75
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
76
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
77
+ accordingly.
78
+ Expected contents:
79
+ `rope_type` (`str`):
80
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
81
+ 'llama3'], with 'default' being the original RoPE implementation.
82
+ `factor` (`float`, *optional*):
83
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
84
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
85
+ original maximum pre-trained length.
86
+ `original_max_position_embeddings` (`int`, *optional*):
87
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
88
+ pretraining.
89
+ `attention_factor` (`float`, *optional*):
90
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
91
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
92
+ `factor` field to infer the suggested value.
93
+ `beta_fast` (`float`, *optional*):
94
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
95
+ ramp function. If unspecified, it defaults to 32.
96
+ `beta_slow` (`float`, *optional*):
97
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
98
+ ramp function. If unspecified, it defaults to 1.
99
+ `short_factor` (`list[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `long_factor` (`list[float]`, *optional*):
104
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
105
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
106
+ size divided by the number of attention heads divided by 2
107
+ `low_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
109
+ `high_freq_factor` (`float`, *optional*):
110
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
111
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
112
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
113
+ layer_types (`list`, *optional*):
114
+ Attention pattern for each layer.
115
+ attention_dropout (`float`, *optional*, defaults to 0.0):
116
+ The dropout ratio for the attention probabilities.
117
+ ```python
118
+ >>> from transformers import Qwen3Model, Qwen3Config
119
+ >>> # Initializing a Qwen3 style configuration
120
+ >>> configuration = Qwen3Config()
121
+ >>> # Initializing a model from the Qwen3-8B style configuration
122
+ >>> model = Qwen3Model(configuration)
123
+ >>> # Accessing the model configuration
124
+ >>> configuration = model.config
125
+ ```"""
126
+
127
+ model_type = "bidirlm"
128
+ keys_to_ignore_at_inference = ["past_key_values"]
129
+
130
+ # Default tensor parallel plan for base model, same than `Qwen3`
131
+ base_model_tp_plan = {
132
+ "layers.*.self_attn.q_proj": "colwise",
133
+ "layers.*.self_attn.k_proj": "colwise",
134
+ "layers.*.self_attn.v_proj": "colwise",
135
+ "layers.*.self_attn.o_proj": "rowwise",
136
+ "layers.*.mlp.gate_proj": "colwise",
137
+ "layers.*.mlp.up_proj": "colwise",
138
+ "layers.*.mlp.down_proj": "rowwise",
139
+ }
140
+ base_model_pp_plan = {
141
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
142
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
143
+ "norm": (["hidden_states"], ["hidden_states"]),
144
+ }
145
+
146
+ def __init__(
147
+ self,
148
+ vocab_size=151936,
149
+ hidden_size=4096,
150
+ intermediate_size=22016,
151
+ num_hidden_layers=32,
152
+ num_attention_heads=32,
153
+ num_key_value_heads=32,
154
+ head_dim=128,
155
+ hidden_act="silu",
156
+ max_position_embeddings=32768,
157
+ initializer_range=0.02,
158
+ rms_norm_eps=1e-6,
159
+ tie_word_embeddings=False,
160
+ rope_theta=10000.0,
161
+ rope_scaling=None,
162
+ attention_bias=False,
163
+ attention_dropout=0.0,
164
+ classifier_pooling="late",
165
+ **kwargs,
166
+ ):
167
+ self.vocab_size = vocab_size
168
+ self.max_position_embeddings = max_position_embeddings
169
+ self.hidden_size = hidden_size
170
+ self.intermediate_size = intermediate_size
171
+ self.num_hidden_layers = num_hidden_layers
172
+ self.num_attention_heads = num_attention_heads
173
+
174
+ # for backward compatibility
175
+ if num_key_value_heads is None:
176
+ num_key_value_heads = num_attention_heads
177
+
178
+ self.num_key_value_heads = num_key_value_heads
179
+ self.head_dim = head_dim
180
+ self.hidden_act = hidden_act
181
+ self.initializer_range = initializer_range
182
+ self.rms_norm_eps = rms_norm_eps
183
+ self.rope_theta = rope_theta
184
+ self.rope_scaling = rope_scaling
185
+ self.attention_bias = attention_bias
186
+ self.attention_dropout = attention_dropout
187
+ self.clf_pooling = classifier_pooling
188
+ # Validate the correctness of rotary position embeddings parameters
189
+ # BC: if there is a 'type' field, move it to 'rope_type'.
190
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
191
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
192
+ rope_config_validation(self)
193
+
194
+ super().__init__(
195
+ tie_word_embeddings=tie_word_embeddings,
196
+ **kwargs,
197
+ )
198
+
199
+
200
+ __all__ = ["BidirLMConfig"]
final_results.png ADDED

Git LFS Details

  • SHA256: 165257135cb40c3b9e7dcec94d225a0cce3a5c12f9ef0d152972eec048d0493a
  • Pointer size: 131 Bytes
  • Size of remote file: 738 kB
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e9585aa599a24d18bfaacadb05b3d302003ea6221c457e721bfdd1bdfc38ae0
3
+ size 1192133232
modeling_bidirlm.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import transformers
4
+ _v = transformers.__version__
5
+ if _v < "4.57.6" or _v >= "5.0.0":
6
+ raise ImportError(
7
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
8
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
9
+ )
10
+
11
+ import torch
12
+ from torch import nn
13
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
14
+
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
17
+ from transformers.modeling_layers import (
18
+ GradientCheckpointingLayer,
19
+ )
20
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
21
+ from transformers.modeling_utils import PreTrainedModel
22
+ from .configuration_bidirlm import BidirLMConfig
23
+
24
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput, TokenClassifierOutput
25
+
26
+ try:
27
+ import flash_attn
28
+ FLASH_ATTN_AVAILABLE = True
29
+ except ImportError:
30
+ FLASH_ATTN_AVAILABLE = False
31
+
32
+ class Qwen3RMSNorm(nn.Module):
33
+ def __init__(self, hidden_size, eps=1e-6):
34
+ """
35
+ Qwen3RMSNorm is equivalent to T5LayerNorm
36
+ """
37
+ super().__init__()
38
+ self.weight = nn.Parameter(torch.ones(hidden_size))
39
+ self.variance_epsilon = eps
40
+
41
+ def forward(self, hidden_states):
42
+ input_dtype = hidden_states.dtype
43
+ hidden_states = hidden_states.to(torch.float32)
44
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
45
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
46
+ return self.weight * hidden_states.to(input_dtype)
47
+
48
+ def extra_repr(self):
49
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
50
+
51
+
52
+ class Qwen3MLP(nn.Module):
53
+ def __init__(self, config):
54
+ super().__init__()
55
+ self.config = config
56
+ self.hidden_size = config.hidden_size
57
+ self.intermediate_size = config.intermediate_size
58
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
59
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
60
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
61
+ self.act_fn = ACT2FN[config.hidden_act]
62
+
63
+ def forward(self, x):
64
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
65
+ return down_proj
66
+
67
+
68
+ def rotate_half(x):
69
+ """Rotates half the hidden dims of the input."""
70
+ x1 = x[..., : x.shape[-1] // 2]
71
+ x2 = x[..., x.shape[-1] // 2 :]
72
+ return torch.cat((-x2, x1), dim=-1)
73
+
74
+
75
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
76
+ """Applies Rotary Position Embedding to the query and key tensors.
77
+
78
+ Args:
79
+ q (`torch.Tensor`): The query tensor.
80
+ k (`torch.Tensor`): The key tensor.
81
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
82
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
83
+ position_ids (`torch.Tensor`, *optional*):
84
+ Deprecated and unused.
85
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
86
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
87
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
88
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
89
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
90
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
91
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
92
+ Returns:
93
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
94
+ """
95
+ cos = cos.unsqueeze(unsqueeze_dim)
96
+ sin = sin.unsqueeze(unsqueeze_dim)
97
+ q_embed = (q * cos) + (rotate_half(q) * sin)
98
+ k_embed = (k * cos) + (rotate_half(k) * sin)
99
+ return q_embed, k_embed
100
+
101
+
102
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
103
+ """
104
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
105
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
106
+ """
107
+ num_key_value_heads, slen, head_dim = hidden_states.shape
108
+ if n_rep == 1:
109
+ return hidden_states
110
+ hidden_states = hidden_states[:, None, :, :].expand(num_key_value_heads, n_rep, slen, head_dim)
111
+ return hidden_states.reshape(num_key_value_heads * n_rep, slen, head_dim)
112
+
113
+ def batch_input_to_cu_seqlens(x: torch.Tensor, attention_mask: torch.Tensor):
114
+ lengths = attention_mask.sum(dim=1)
115
+ max_seqlen = int(lengths.max().item())
116
+ cu_seqlens = torch.zeros(lengths.size(0) + 1, dtype=torch.int32, device=x.device)
117
+ cu_seqlens[1:] = torch.cumsum(lengths, dim=0)
118
+ x = x[attention_mask.bool()]
119
+ return x, cu_seqlens, max_seqlen
120
+
121
+ def cu_seqlens_to_batch_input(x: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int):
122
+ B = cu_seqlens.size(0) - 1
123
+ D = x.size(1)
124
+ idx = torch.arange(max_seqlen, device=x.device).expand(B, max_seqlen)
125
+ lens = (cu_seqlens[1:] - cu_seqlens[:-1]).unsqueeze(1)
126
+ mask = idx < lens
127
+ base = cu_seqlens[:-1].unsqueeze(1)
128
+ gather_idx = (idx + base) * mask
129
+ out = torch.zeros(B, max_seqlen, D, device=x.device, dtype=x.dtype)
130
+ out[mask] = x[gather_idx[mask]]
131
+ return out
132
+
133
+ def cu_attention_weight_to_batch(hidden_states, cu_seqlens, max_seqlen):
134
+ H, T, _ = hidden_states.shape
135
+ device = hidden_states.device
136
+ cu_seqlens = cu_seqlens.to(device, dtype=torch.long)
137
+
138
+ B = cu_seqlens.numel() - 1
139
+ start = cu_seqlens[:-1]
140
+ end = cu_seqlens[1:]
141
+ L = end - start
142
+
143
+ p = torch.arange(max_seqlen, device=device)
144
+ valid = p.unsqueeze(0) < L.unsqueeze(1)
145
+
146
+ rel = p.unsqueeze(0)
147
+ abs_idx = start.unsqueeze(1) + rel
148
+ abs_idx = torch.where(valid, abs_idx, torch.zeros_like(abs_idx))
149
+
150
+ attn = hidden_states.unsqueeze(0).expand(B, -1, -1, -1)
151
+
152
+ row_index = abs_idx[:, None, :, None].expand(B, H, max_seqlen, T)
153
+ attn_rows = torch.gather(attn, dim=2, index=row_index)
154
+
155
+ col_index = abs_idx[:, None, None, :].expand(B, H, max_seqlen, max_seqlen)
156
+ attn_padded = torch.gather(attn_rows, dim=3, index=col_index)
157
+
158
+ mask = valid.to(attn_padded.dtype)
159
+ attn_padded = attn_padded * mask[:, None, :, None] * mask[:, None, None, :]
160
+
161
+ return attn_padded
162
+
163
+ def create_packed_seqs_mask(
164
+ cu_seqlens: torch.Tensor,
165
+ causal: bool = True,
166
+ device: torch.device = torch.device("cpu"),
167
+ ) -> torch.Tensor:
168
+ """
169
+ Create a causal or non-causal attention mask for packed sequences.
170
+
171
+ Args:
172
+ cu_seqlens (torch.Tensor): Cumulative sequence lengths of shape [batch + 1].
173
+ is_causal (bool): If True, create a causal (lower triangular) mask within
174
+ each sequence. If False, a full attention mask is created within each sequence.
175
+ device (torch.device): Target device for the mask.
176
+
177
+ Returns:
178
+ torch.Tensor: Attention mask of shape [total_len, total_len] with 0.0 (allowed)
179
+ and -inf (masked).
180
+ """
181
+ total_len = cu_seqlens[-1].item()
182
+ seq_lengths = cu_seqlens[1:] - cu_seqlens[:-1]
183
+
184
+ seq_indices = torch.repeat_interleave(
185
+ torch.arange(len(seq_lengths), device=device),
186
+ seq_lengths
187
+ )
188
+
189
+ seq_mask = seq_indices.unsqueeze(0) == seq_indices.unsqueeze(1)
190
+
191
+ if causal:
192
+ causal_mask = torch.tril(torch.ones(total_len, total_len, device=device, dtype=torch.bool))
193
+ combined_mask = seq_mask & causal_mask
194
+ else:
195
+ combined_mask = seq_mask
196
+
197
+ attention_mask = torch.full((total_len, total_len), float('-inf'), device=device)
198
+ attention_mask.masked_fill_(combined_mask, 0.0)
199
+
200
+ return attention_mask
201
+
202
+ def sdpa_attention_forward(
203
+ q, k, v,
204
+ cu_seqlens,
205
+ scaling,
206
+ dropout: float = 0.0,
207
+ causal: bool = True
208
+ ):
209
+ """Compute scaled dot-product attention for packed sequences."""
210
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) * scaling
211
+
212
+ mask = create_packed_seqs_mask(cu_seqlens, causal, q.device)
213
+ attn_weights = attn_weights + mask
214
+
215
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
216
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout)
217
+ attn_output = torch.matmul(attn_weights, v)
218
+ attn_output = attn_output.transpose(0, 1).contiguous()
219
+
220
+ return attn_output, attn_weights
221
+
222
+ class Qwen3Attention(nn.Module):
223
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
224
+
225
+ def __init__(self, config: BidirLMConfig):
226
+ super().__init__()
227
+ self.config = config
228
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
229
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
230
+ self.scaling = self.head_dim**-0.5
231
+ self.attention_dropout = config.attention_dropout
232
+
233
+ self.q_proj = nn.Linear(
234
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
235
+ )
236
+ self.k_proj = nn.Linear(
237
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
238
+ )
239
+ self.v_proj = nn.Linear(
240
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
241
+ )
242
+ self.o_proj = nn.Linear(
243
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
244
+ )
245
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
246
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
247
+
248
+ def forward(
249
+ self,
250
+ hidden_states: torch.Tensor,
251
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
252
+ cu_seqlens: Optional[torch.Tensor],
253
+ max_seqlen: Optional[int],
254
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
255
+ input_shape = hidden_states.shape[:-1]
256
+ hidden_shape = (*input_shape, -1, self.head_dim)
257
+
258
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(0, 1)
259
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(0, 1)
260
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(0, 1)
261
+
262
+ query_states, key_states = query_states.unsqueeze(0), key_states.unsqueeze(0),
263
+ cos, sin = position_embeddings
264
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
265
+ query_states, key_states = query_states.squeeze(0), key_states.squeeze(0),
266
+
267
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
268
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
269
+
270
+ if self.config._attn_implementation == "flash_attention_2":
271
+ attn_weights = None
272
+ attn_output = flash_attn.flash_attn_varlen_func(
273
+ query_states.transpose(0, 1),
274
+ key_states.transpose(0, 1),
275
+ value_states.transpose(0, 1),
276
+ cu_seqlens,
277
+ cu_seqlens,
278
+ max_seqlen_q=max_seqlen,
279
+ max_seqlen_k=max_seqlen,
280
+ dropout_p=self.attention_dropout if self.training else 0.0,
281
+ softmax_scale=self.scaling,
282
+ causal=False,
283
+ ).contiguous()
284
+ else:
285
+ attn_output, attn_weights = sdpa_attention_forward(
286
+ query_states,
287
+ key_states,
288
+ value_states,
289
+ cu_seqlens=cu_seqlens,
290
+ dropout=self.attention_dropout if self.training else 0.0,
291
+ scaling=self.scaling,
292
+ causal=False,
293
+ )
294
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
295
+ attn_output = self.o_proj(attn_output)
296
+
297
+ return attn_output, attn_weights
298
+
299
+
300
+ class Qwen3EncoderLayer(GradientCheckpointingLayer):
301
+ def __init__(self, config: BidirLMConfig):
302
+ super().__init__()
303
+ self.hidden_size = config.hidden_size
304
+
305
+ self.self_attn = Qwen3Attention(config=config)
306
+
307
+ self.mlp = Qwen3MLP(config)
308
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
309
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
310
+
311
+ def forward(
312
+ self,
313
+ hidden_states: torch.Tensor,
314
+ cu_seqlens: Optional[torch.Tensor] = None,
315
+ max_seqlen: Optional[int] = None,
316
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
317
+ output_attentions: Optional[bool] = False,
318
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
319
+ residual = hidden_states
320
+ hidden_states = self.input_layernorm(hidden_states)
321
+
322
+ hidden_states, self_attn_weights = self.self_attn(
323
+ hidden_states=hidden_states,
324
+ cu_seqlens=cu_seqlens,
325
+ max_seqlen=max_seqlen,
326
+ position_embeddings=position_embeddings,
327
+ )
328
+ hidden_states = residual + hidden_states
329
+
330
+ residual = hidden_states
331
+ hidden_states = self.post_attention_layernorm(hidden_states)
332
+ hidden_states = self.mlp(hidden_states)
333
+ hidden_states = residual + hidden_states
334
+
335
+ outputs = (hidden_states,)
336
+ if output_attentions:
337
+ outputs += (self_attn_weights,)
338
+
339
+ return outputs
340
+
341
+
342
+ class BidirLMPreTrainedModel(PreTrainedModel):
343
+ config: BidirLMConfig
344
+ base_model_prefix = "model"
345
+ _supports_flash_attn = True
346
+ _supports_sdpa = True
347
+ _can_record_outputs = {}
348
+
349
+
350
+ class Qwen3RotaryEmbedding(nn.Module):
351
+ def __init__(self, config: BidirLMConfig, device=None):
352
+ super().__init__()
353
+ # BC: "rope_type" was originally "type"
354
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
355
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
356
+ else:
357
+ self.rope_type = "default"
358
+ self.max_seqlen_cached = config.max_position_embeddings
359
+ self.original_max_seqlen = config.max_position_embeddings
360
+
361
+ self.config = config
362
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
363
+
364
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
365
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
366
+ self.original_inv_freq = self.inv_freq
367
+
368
+ @torch.no_grad()
369
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
370
+ def forward(self, x, position_ids):
371
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
372
+ position_ids_expanded = position_ids[:, None, :].float()
373
+
374
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
375
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
376
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
377
+ emb = torch.cat((freqs, freqs), dim=-1)
378
+ cos = emb.cos() * self.attention_scaling
379
+ sin = emb.sin() * self.attention_scaling
380
+
381
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
382
+
383
+
384
+ class BidirLMModel(BidirLMPreTrainedModel):
385
+ def __init__(self, config: BidirLMConfig):
386
+ super().__init__(config)
387
+ self.padding_idx = config.pad_token_id
388
+ self.vocab_size = config.vocab_size
389
+
390
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
391
+ self.layers = nn.ModuleList([Qwen3EncoderLayer(config) for _ in range(config.num_hidden_layers)])
392
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
393
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
394
+ self.gradient_checkpointing = False
395
+
396
+ self.mask_converter = AttentionMaskConverter(True)
397
+ self.post_init()
398
+
399
+ def forward(
400
+ self,
401
+ input_ids: torch.LongTensor,
402
+ attention_mask: Optional[torch.Tensor] = None,
403
+ *,
404
+ output_attentions: Optional[bool] = None,
405
+ output_hidden_states: Optional[bool] = None,
406
+ return_dict: Optional[bool] = None,
407
+ **kwargs
408
+ ) -> tuple[torch.Tensor] | BaseModelOutput:
409
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
410
+ output_hidden_states = (
411
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
412
+ )
413
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
414
+ all_hidden_states = () if output_hidden_states else None
415
+ all_self_attns = () if output_attentions else None
416
+
417
+ # For MNTP XP
418
+ batch_size, seq_len = input_ids.size()
419
+ new_input_ids = torch.empty((batch_size, seq_len + 1), dtype=input_ids.dtype, device=input_ids.device)
420
+ new_input_ids[:, 0] = 151644
421
+ new_input_ids[:, 1:] = input_ids
422
+
423
+ if attention_mask is not None:
424
+ new_attention_mask = torch.empty((batch_size, seq_len + 1), dtype=attention_mask.dtype, device=attention_mask.device)
425
+ new_attention_mask[:, 0] = 1
426
+ new_attention_mask[:, 1:] = attention_mask
427
+ attention_mask = new_attention_mask
428
+ input_ids, cu_seqlens, max_seqlen = batch_input_to_cu_seqlens(new_input_ids, attention_mask)
429
+ else:
430
+ input_ids = new_input_ids
431
+
432
+ hidden_states = self.embed_tokens(input_ids)
433
+ position_ids = torch.arange(len(input_ids), device=input_ids.device).unsqueeze(0)
434
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
435
+
436
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
437
+ if output_hidden_states:
438
+ if attention_mask is not None:
439
+ all_hidden_states += (cu_seqlens_to_batch_input(hidden_states, cu_seqlens, attention_mask.shape[-1])[0],)
440
+ else:
441
+ all_hidden_states += (hidden_states,)
442
+
443
+ layer_outputs = encoder_layer(
444
+ hidden_states,
445
+ cu_seqlens=cu_seqlens,
446
+ max_seqlen=max_seqlen,
447
+ position_embeddings=position_embeddings,
448
+ output_attentions=output_attentions,
449
+ )
450
+
451
+ hidden_states = layer_outputs[0]
452
+ if output_attentions:
453
+ if attention_mask is not None:
454
+ all_self_attns += (cu_attention_weight_to_batch(layer_outputs[1], cu_seqlens, attention_mask.shape[-1]),)
455
+ else:
456
+ all_self_attns += (layer_outputs[1],)
457
+
458
+ hidden_states = self.norm(hidden_states)
459
+ if attention_mask is not None:
460
+ hidden_states = cu_seqlens_to_batch_input(hidden_states, cu_seqlens, attention_mask.shape[-1])
461
+ if output_hidden_states:
462
+ all_hidden_states += (hidden_states,)
463
+
464
+ # For MNTP XP
465
+ output = BaseModelOutput(
466
+ last_hidden_state=hidden_states[:, :-1, :],
467
+ hidden_states=tuple(h[:, :-1, :] for h in all_hidden_states) if all_hidden_states is not None else None,
468
+ attentions=tuple(a[:, :, :-1, :-1] for a in all_self_attns) if all_self_attns is not None else None,
469
+ )
470
+ return output if return_dict else output.to_tuple()
471
+
472
+ class BidirLMForMaskedLM(BidirLMPreTrainedModel):
473
+ config_class = BidirLMConfig
474
+ _tied_weights_keys = ["lm_head.weight"]
475
+
476
+ def __init__(self, config):
477
+ super().__init__(config)
478
+ self.model = BidirLMModel(config)
479
+ self.vocab_size = config.vocab_size
480
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
481
+
482
+ self.post_init()
483
+
484
+ def forward(
485
+ self,
486
+ input_ids: torch.LongTensor = None,
487
+ *,
488
+ attention_mask: Optional[torch.Tensor] = None,
489
+ labels: Optional[torch.LongTensor] = None,
490
+ output_attentions: Optional[bool] = None,
491
+ output_hidden_states: Optional[bool] = None,
492
+ return_dict: Optional[bool] = None,
493
+ **kwargs
494
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
495
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
496
+ encoder_output = self.model(
497
+ input_ids=input_ids,
498
+ attention_mask=attention_mask,
499
+ output_attentions=output_attentions,
500
+ output_hidden_states=output_hidden_states,
501
+ return_dict=return_dict,
502
+ )
503
+ logits = self.lm_head(encoder_output[0])
504
+
505
+ loss = None
506
+ if labels is not None:
507
+ loss = self.loss_function(
508
+ logits, labels, vocab_size=self.config.vocab_size
509
+ )
510
+
511
+ output = MaskedLMOutput(
512
+ loss=loss,
513
+ logits=logits,
514
+ hidden_states=encoder_output.hidden_states,
515
+ attentions=encoder_output.attentions,
516
+ )
517
+ return output if return_dict else output.to_tuple()
518
+
519
+ class BidirLMForSequenceClassification(BidirLMPreTrainedModel):
520
+ def __init__(self, config: BidirLMConfig):
521
+ super().__init__(config)
522
+ self.num_labels = config.num_labels
523
+ self.clf_pooling = config.clf_pooling
524
+
525
+ self.model = BidirLMModel(config)
526
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
527
+ self.activation = nn.GELU()
528
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
529
+ self.post_init()
530
+
531
+ def forward(
532
+ self,
533
+ input_ids: Optional[torch.LongTensor] = None,
534
+ attention_mask: Optional[torch.Tensor] = None,
535
+ labels: Optional[torch.LongTensor] = None,
536
+ output_attentions: Optional[bool] = None,
537
+ output_hidden_states: Optional[bool] = None,
538
+ return_dict: Optional[bool] = None,
539
+ **kwargs
540
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
541
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
542
+
543
+ encoder_output = self.model(
544
+ input_ids,
545
+ attention_mask=attention_mask,
546
+ output_attentions=output_attentions,
547
+ output_hidden_states=output_hidden_states,
548
+ return_dict=return_dict,
549
+ )
550
+ last_hidden_state = encoder_output[0]
551
+
552
+ if self.clf_pooling in ["bos", "mean"]:
553
+ if self.clf_pooling == "bos":
554
+ pooled_output = last_hidden_state[:, 0]
555
+
556
+ elif self.clf_pooling == "mean":
557
+ if attention_mask is None:
558
+ pooled_output = last_hidden_state.mean(dim=1)
559
+ else:
560
+ pooled_output = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1)
561
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
562
+
563
+ pooled_output = self.dense(pooled_output)
564
+ pooled_output = self.activation(pooled_output)
565
+ logits = self.classifier(pooled_output)
566
+ elif self.clf_pooling == "late":
567
+ x = self.dense(last_hidden_state)
568
+ x = self.activation(x)
569
+ logits = self.classifier(x)
570
+ if attention_mask is None:
571
+ logits = logits.mean(dim=1)
572
+ else:
573
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
574
+ logits /= attention_mask.sum(dim=1, keepdim=True)
575
+
576
+ loss = None
577
+ if labels is not None:
578
+ labels = labels.to(logits.device)
579
+ if self.config.problem_type is None:
580
+ if self.num_labels == 1:
581
+ self.config.problem_type = "regression"
582
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
583
+ self.config.problem_type = "single_label_classification"
584
+ else:
585
+ self.config.problem_type = "multi_label_classification"
586
+
587
+ if self.config.problem_type == "regression":
588
+ loss_fct = MSELoss()
589
+ if self.num_labels == 1:
590
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
591
+ else:
592
+ loss = loss_fct(logits, labels)
593
+ elif self.config.problem_type == "single_label_classification":
594
+ loss_fct = CrossEntropyLoss()
595
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
596
+ elif self.config.problem_type == "multi_label_classification":
597
+ loss_fct = BCEWithLogitsLoss()
598
+ loss = loss_fct(logits, labels)
599
+
600
+ output = SequenceClassifierOutput(
601
+ loss=loss,
602
+ logits=logits,
603
+ hidden_states=encoder_output.hidden_states,
604
+ attentions=encoder_output.attentions,
605
+ )
606
+ return output if return_dict else output.to_tuple()
607
+
608
+ class BidirLMForTokenClassification(BidirLMPreTrainedModel):
609
+ def __init__(self, config: BidirLMConfig):
610
+ super().__init__(config)
611
+ self.num_labels = config.num_labels
612
+
613
+ self.model = BidirLMModel(config)
614
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
615
+ self.post_init()
616
+
617
+ def forward(
618
+ self,
619
+ input_ids: Optional[torch.LongTensor] = None,
620
+ attention_mask: Optional[torch.Tensor] = None,
621
+ position_ids: Optional[torch.LongTensor] = None,
622
+ inputs_embeds: Optional[torch.FloatTensor] = None,
623
+ labels: Optional[torch.LongTensor] = None,
624
+ use_cache: Optional[bool] = None,
625
+ output_attentions: Optional[bool] = None,
626
+ output_hidden_states: Optional[bool] = None,
627
+ return_dict: Optional[bool] = None,
628
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
629
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
630
+
631
+ outputs = self.model(
632
+ input_ids,
633
+ attention_mask=attention_mask,
634
+ position_ids=position_ids,
635
+ inputs_embeds=inputs_embeds,
636
+ use_cache=use_cache,
637
+ output_attentions=output_attentions,
638
+ output_hidden_states=output_hidden_states,
639
+ return_dict=return_dict,
640
+ )
641
+ sequence_output = outputs[0]
642
+ logits = self.classifier(sequence_output)
643
+
644
+ loss = None
645
+ if labels is not None:
646
+ loss_fct = CrossEntropyLoss()
647
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
648
+
649
+ if not return_dict:
650
+ output = (logits,) + outputs[2:]
651
+ return ((loss,) + output) if loss is not None else output
652
+
653
+ return TokenClassifierOutput(
654
+ loss=loss,
655
+ logits=logits,
656
+ hidden_states=outputs.hidden_states,
657
+ attentions=outputs.attentions,
658
+ )
659
+
660
+ __all__ = [
661
+ "BidirLMPreTrainedModel",
662
+ "BidirLMModel",
663
+ "BidirLMForMaskedLM",
664
+ "BidirLMForSequenceClassification",
665
+ "BidirLMForTokenClassification",
666
+ ]
modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
mteb_v2_eval_prompts.json ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "AmazonCounterfactualClassification": "Given an Amazon review, judge whether it is counterfactual.",
3
+ "AmazonPolarityClassification": "Classifying Amazon reviews into positive or negative sentiment",
4
+ "AmazonReviewsClassification": "Classifying the given Amazon review into its appropriate rating category",
5
+ "Banking77Classification": "Given an online banking query, find the corresponding intents",
6
+ "EmotionClassification": "Classify the emotion expressed in the given Twitter message into one of the six emotions: anger, fear, joy, love, sadness, and surprise",
7
+ "ImdbClassification": "Classifying the sentiment expressed in the given movie review text from the IMDB dataset",
8
+ "MassiveIntentClassification": "Given a user utterance as query, find the user intents",
9
+ "MassiveScenarioClassification": "Given a user utterance as query, find the user scenarios",
10
+ "MTOPDomainClassification": "Classifying the intent domain of the given utterance in task-oriented conversation",
11
+ "MTOPIntentClassification": "Classifying the intent of the given utterance in task-oriented conversation",
12
+ "ToxicConversationsClassification": "Classifying the given comments as either toxic or not toxic",
13
+ "TweetSentimentExtractionClassification": "Classifying the sentiment of a given tweet as either positive, negative, or neutral",
14
+ "TNews": "Categorizing the given news title",
15
+ "IFlyTek": "Given an App description text, find the appropriate fine-grained category",
16
+ "MultilingualSentiment": "Classifying sentiment of the customer review into positive, neutral, or negative",
17
+ "JDReview": "Classifying sentiment of the customer review for iPhoneinto positive or negative",
18
+ "OnlineShopping": "Classifying sentiment of the customer reviewinto positive or negative",
19
+ "Waimai": "Classify the customer review from a food takeaway platform into positive or negative",
20
+ "ArxivClusteringP2P": "Identify the main and secondary category of Arxiv papers based on the titles and abstracts",
21
+ "ArxivClusteringS2S": "Identify the main and secondary category of Arxiv papers based on the titles",
22
+ "BiorxivClusteringP2P": "Identify the main category of Biorxiv papers based on the titles and abstracts",
23
+ "BiorxivClusteringS2S": "Identify the main category of Biorxiv papers based on the titles",
24
+ "MedrxivClusteringP2P": "Identify the main category of Medrxiv papers based on the titles and abstracts",
25
+ "MedrxivClusteringS2S": "Identify the main category of Medrxiv papers based on the titles",
26
+ "RedditClustering": "Identify the topic or theme of Reddit posts based on the titles",
27
+ "RedditClusteringP2P": "Identify the topic or theme of Reddit posts based on the titles and posts",
28
+ "StackExchangeClustering": "Identify the topic or theme of StackExchange posts based on the titles",
29
+ "StackExchangeClusteringP2P": "Identify the topic or theme of StackExchange posts based on the given paragraphs",
30
+ "TwentyNewsgroupsClustering": "Identify the topic or theme of the given news articles",
31
+ "CLSClusteringS2S": "Identify the main category of scholar papers based on the titles",
32
+ "CLSClusteringP2P": "Identify the main category of scholar papers based on the titles and abstracts",
33
+ "ThuNewsClusteringS2S": "Identify the topic or theme of the given news articles based on the titles",
34
+ "ThuNewsClusteringP2P": "Identify the topic or theme of the given news articles based on the titles and contents",
35
+ "AskUbuntuDupQuestions": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
36
+ "MindSmallReranking": "Given a query, retrieve documents that answer the query.",
37
+ "SciDocsRR": "Given a query, retrieve documents that answer the query.",
38
+ "StackOverflowDupQuestions": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
39
+ "SprintDuplicateQuestions": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
40
+ "TwitterSemEval2015": "Retrieve semantically similar text.",
41
+ "TwitterURLCorpus": "Retrieve semantically similar text.",
42
+ "T2Reranking": "Given a query, retrieve documents that answer the query.",
43
+ "MmarcoReranking": "Given a query, retrieve documents that answer the query.",
44
+ "CMedQAv1": "Given a query, retrieve documents that answer the query.",
45
+ "CMedQAv2": "Given a query, retrieve documents that answer the query.",
46
+ "Ocnli": "Retrieve semantically similar text.",
47
+ "Cmnli": "Retrieve semantically similar text.",
48
+ "ArguAna": {
49
+ "query": "Given a claim, retrieve documents that support or refute the claim",
50
+ "passage": "Given a claim, retrieve documents that support or refute the claim"
51
+ },
52
+ "ClimateFEVER": "Given a claim, retrieve documents that support or refute the claim",
53
+ "ClimateFEVERHardNegatives": "Given a claim, retrieve documents that support or refute the claim",
54
+ "DBPedia": "Given a query, retrieve documents that answer the query.",
55
+ "FEVER": "Given a claim, retrieve documents that support or refute the claim",
56
+ "FEVERHardNegatives": "Given a claim, retrieve documents that support or refute the claim",
57
+ "FiQA2018": "Given a query, retrieve documents that answer the query.",
58
+ "HotpotQA": "Given a multi-hop question, retrieve documents that can help answer the question",
59
+ "HotpotQAHardNegatives": "Given a multi-hop question, retrieve documents that can help answer the question",
60
+ "MSMARCO": "Given a web search query, retrieve relevant passages that answer the query",
61
+ "NFCorpus": "Given a question, retrieve relevant documents that best answer the question",
62
+ "NQ": "Given a question, retrieve Wikipedia passages that answer the question",
63
+ "QuoraRetrieval": "Given a query, retrieve documents that answer the query.",
64
+ "SCIDOCS": "Given a query, retrieve documents that answer the query.",
65
+ "SciFact": "Given a scientific claim, retrieve documents that support or refute the claim",
66
+ "Touche2020": "Given a query, retrieve documents that answer the query.",
67
+ "Touche2020Retrieval.v3": "Given a query, retrieve documents that answer the query.",
68
+ "TRECCOVID": "Given a query, retrieve documents that answer the query.",
69
+ "T2Retrieval": "Given a question, retrieve passages that answer the question",
70
+ "MMarcoRetrieval": "Given a web search query, retrieve relevant passages that answer the query",
71
+ "DuRetrieval": "Given a question, retrieve passages that answer the question",
72
+ "CovidRetrieval": "Given a query on COVID-19, retrieve documents that answer the query",
73
+ "CmedqaRetrieval": "Given a query, retrieve documents that answer the query.",
74
+ "EcomRetrieval": "Given a query, retrieve documents that answer the query.",
75
+ "MedicalRetrieval": "Given a query, retrieve documents that answer the query.",
76
+ "VideoRetrieval": "Given a query, retrieve documents that answer the query.",
77
+ "STSBenchmarkMultilingualSTS": "Retrieve semantically similar text",
78
+ "SICKFr": "Retrieve semantically similar text",
79
+ "SummEvalFr": "Retrieve semantically similar text.",
80
+ "MasakhaNEWSClassification": "Categorizing the given news title",
81
+ "OpusparcusPC": "Retrieve semantically similar text",
82
+ "PawsX": "Retrieve semantically similar text",
83
+ "AlloProfClusteringP2P": "Identify the main category of scholar papers based on the titles and abstracts",
84
+ "AlloProfClusteringS2S": "Identify the main category of scholar papers based on the titles",
85
+ "HALClusteringS2S": "Identify the main category of scholar papers based on the titles",
86
+ "MasakhaNEWSClusteringP2P": "Identify the topic or theme of the given news articles based on the titles and contents",
87
+ "MasakhaNEWSClusteringS2S": "Identify the topic or theme of the given news articles based on the titles",
88
+ "MLSUMClusteringP2P": "Identify the topic or theme of Reddit posts based on the titles and posts",
89
+ "MLSUMClusteringS2S": "Identify the topic or theme of Reddit posts based on the titles",
90
+ "SyntecReranking": "Given a question, retrieve passages that answer the question",
91
+ "AlloprofReranking": "Given a question, retrieve passages that answer the question",
92
+ "AlloprofRetrieval": "Given a question, retrieve passages that answer the question",
93
+ "BSARDRetrieval": "Given a question, retrieve passages that answer the question",
94
+ "SyntecRetrieval": "Given a question, retrieve passages that answer the question",
95
+ "XPQARetrieval": "Given a question, retrieve passages that answer the question",
96
+ "MintakaRetrieval": "Given a question, retrieve passages that answer the question",
97
+ "CBD": "Classifying the sentiment of a given tweet as either positive, negative, or neutral",
98
+ "PolEmo2.0-IN": "Classifying sentiment of the customer review into positive, neutral, or negative",
99
+ "PolEmo2.0-OUT": "Classifying sentiment of the customer review into positive, neutral, or negative",
100
+ "AllegroReviews": "Classifying sentiment of the customer review into positive, neutral, or negative",
101
+ "PAC": "Classify the sentence into one of the two types: \"BEZPIECZNE_POSTANOWIENIE_UMOWNE\" and \"KLAUZULA_ABUZYWNA\"",
102
+ "SICK-E-PL": "Retrieve semantically similar text",
103
+ "SICK-R-PL": "Retrieve semantically similar text",
104
+ "STS22": "Retrieve semantically similar text",
105
+ "AFQMC": "Retrieve semantically similar text",
106
+ "BQ": "Retrieve semantically similar text",
107
+ "LCQMC": "Retrieve semantically similar text",
108
+ "PAWSX": "Retrieve semantically similar text",
109
+ "QBQTC": "Retrieve semantically similar text",
110
+ "STS12": "Retrieve semantically similar text",
111
+ "PPC": "Retrieve semantically similar text",
112
+ "CDSC-E": "Retrieve semantically similar text",
113
+ "PSC": "Retrieve semantically similar text",
114
+ "8TagsClustering": "Identify the topic or theme of the given news articles",
115
+ "ArguAna-PL": "Given a claim, retrieve documents that support or refute the claim",
116
+ "DBPedia-PL": "Given a query, retrieve documents that answer the query.",
117
+ "FiQA-PL": "Given a query, retrieve documents that answer the query.",
118
+ "HotpotQA-PL": "Given a multi-hop question, retrieve documents that can help answer the question",
119
+ "MSMARCO-PL": "Given a web search query, retrieve relevant passages that answer the query",
120
+ "NFCorpus-PL": "Given a question, retrieve relevant documents that best answer the question",
121
+ "NQ-PL": "Given a question, retrieve Wikipedia passages that answer the question",
122
+ "Quora-PL": "Given a query, retrieve documents that answer the query.",
123
+ "SCIDOCS-PL": "Given a query, retrieve documents that answer the query.",
124
+ "SciFact-PL": "Given a scientific claim, retrieve documents that support or refute the claim",
125
+ "TRECCOVID-PL": "Given a query, retrieve documents that answer the query.",
126
+ "GeoreviewClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
127
+ "HeadlineClassification": "Categorizing the given news title",
128
+ "InappropriatenessClassification": "Classifying the given comments as either toxic or not toxic",
129
+ "KinopoiskClassification": "Classifying the sentiment expressed in the given movie review text from the IMDB dataset",
130
+ "RuReviewsClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
131
+ "RuSciBenchGRNTIClassification": "Categorizing the given news title",
132
+ "RuSciBenchOECDClassification": "Categorizing the given news title",
133
+ "GeoreviewClusteringP2P": "Identify the topic or theme of Reddit posts based on the titles and posts",
134
+ "RuSciBenchGRNTIClusteringP2P": "Identify the main category of scholar papers based on the titles and abstracts",
135
+ "RuSciBenchOECDClusteringP2P": "Identify the main category of scholar papers based on the titles and abstracts",
136
+ "TERRa": "Retrieve semantically similar text.",
137
+ "RuBQReranking": "Given a question, retrieve Wikipedia passages that answer the question",
138
+ "RiaNewsRetrieval": "Given a query, retrieve documents that answer the query.",
139
+ "RuBQRetrieval": "Given a question, retrieve Wikipedia passages that answer the question",
140
+ "RUParaPhraserSTS": "Retrieve semantically similar text",
141
+ "RuSTSBenchmarkSTS": "Retrieve semantically similar text",
142
+ "AppsRetrieval": "Given a query, retrieve documents that answer the query.",
143
+ "COIRCodeSearchNetRetrieval": "Given a query, retrieve documents that answer the query.",
144
+ "CodeEditSearchRetrieval": "Given a query, retrieve documents that answer the query.",
145
+ "CodeFeedbackMT": "Given a query, retrieve documents that answer the query.",
146
+ "CodeFeedbackST": "Given a query, retrieve documents that answer the query.",
147
+ "CodeSearchNetCCRetrieval": "Given a query, retrieve documents that answer the query.",
148
+ "CodeSearchNetRetrieval": "Given a query, retrieve documents that answer the query.",
149
+ "CodeTransOceanContest": "Given a query, retrieve documents that answer the query.",
150
+ "CodeTransOceanDL": "Given a query, retrieve documents that answer the query.",
151
+ "CosQA": "Given a query, retrieve documents that answer the query.",
152
+ "StackOverflowQA": "Given a query, retrieve documents that answer the query.",
153
+ "SyntheticText2SQL": "Given a query, retrieve documents that answer the query.",
154
+ "BibleNLPBitextMining": "Retrieve semantically similar text.",
155
+ "BUCC.v2": "Retrieve semantically similar text.",
156
+ "DiaBlaBitextMining": "Retrieve semantically similar text.",
157
+ "FloresBitextMining": "Retrieve semantically similar text.",
158
+ "IN22GenBitextMining": "Retrieve semantically similar text.",
159
+ "IndicGenBenchFloresBitextMining": "Retrieve semantically similar text.",
160
+ "NollySentiBitextMining": "Retrieve semantically similar text.",
161
+ "NTREXBitextMining": "Retrieve semantically similar text.",
162
+ "NusaTranslationBitextMining": "Retrieve semantically similar text.",
163
+ "NusaXBitextMining": "Retrieve semantically similar text.",
164
+ "Tatoeba": "Retrieve semantically similar text.",
165
+ "BulgarianStoreReviewSentimentClassfication": "Classifying sentiment of the customer review into positive, neutral, or negative",
166
+ "CzechProductReviewSentimentClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
167
+ "GreekLegalCodeClassification": "Categorizing the given news title",
168
+ "DBpediaClassification": "Given an App description text, find the appropriate fine-grained category",
169
+ "FinancialPhrasebankClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
170
+ "PoemSentimentClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
171
+ "TweetTopicSingleClassification": "Categorizing the given news title",
172
+ "EstonianValenceClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
173
+ "FilipinoShopeeReviewsClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
174
+ "GujaratiNewsClassification": "Categorizing the given news title",
175
+ "SentimentAnalysisHindi": "Classifying sentiment of the customer review into positive, neutral, or negative",
176
+ "IndonesianIdClickbaitClassification": "Categorizing the given news title",
177
+ "ItaCaseholdClassification": "Categorizing the given news title",
178
+ "KorSarcasmClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
179
+ "KurdishSentimentClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
180
+ "MacedonianTweetSentimentClassification": "Classifying the sentiment of a given tweet as either positive, negative, or neutral",
181
+ "AfriSentiClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
182
+ "CataloniaTweetClassification": "Classifying the sentiment of a given tweet as either positive, negative, or neutral",
183
+ "CyrillicTurkicLangClassification": "Given a text, classify its language",
184
+ "IndicLangClassification": "Given a text, classify its language",
185
+ "MultiHateClassification": "Classifying the given comments as either toxic or not toxic",
186
+ "NusaParagraphEmotionClassification": "Classify the emotion expressed in the given Twitter message into one of the six emotions: anger, fear, joy, love, sadness, and surprise",
187
+ "NusaX-senti": "Classifying sentiment of the customer review into positive, neutral, or negative",
188
+ "SwissJudgementClassification": "Classifying sentiment of the customer review into positive, neutral, or negative",
189
+ "NepaliNewsClassification": "Categorizing the given news title",
190
+ "OdiaNewsClassification": "Categorizing the given news title",
191
+ "PunjabiNewsClassification": "Categorizing the given news title",
192
+ "SinhalaNewsClassification": "Categorizing the given news title",
193
+ "CSFDSKMovieReviewSentimentClassification": "Classifying the sentiment expressed in the given movie review text from the IMDB dataset",
194
+ "SiswatiNewsClassification": "Categorizing the given news title",
195
+ "SlovakMovieReviewSentimentClassification": "Classifying the sentiment expressed in the given movie review text from the IMDB dataset",
196
+ "SwahiliNewsClassification": "Categorizing the given news title",
197
+ "TswanaNewsClassification": "Categorizing the given news title",
198
+ "IsiZuluNewsClassification": "Categorizing the given news title",
199
+ "WikiCitiesClustering": "Identify the topic or theme of the given news articles",
200
+ "RomaniBibleClustering": "Identify the topic or theme of the given news articles",
201
+ "ArXivHierarchicalClusteringP2P": "Identify the main and secondary category of Arxiv papers based on the titles and abstracts",
202
+ "ArXivHierarchicalClusteringS2S": "Identify the main and secondary category of Arxiv papers based on the titles",
203
+ "BigPatentClustering.v2": "Identify the main category of scholar papers based on the titles and abstracts",
204
+ "AlloProfClusteringS2S.v2": "Identify the main category of scholar papers based on the titles",
205
+ "HALClusteringS2S.v2": "Identify the main category of scholar papers based on the titles",
206
+ "SIB200ClusteringS2S": "Identify the topic or theme of the given news articles",
207
+ "WikiClusteringP2P.v2": "Identify the topic or theme of the given news articles",
208
+ "PlscClusteringP2P.v2": "Identify the main category of scholar papers based on the titles and abstracts",
209
+ "KorHateSpeechMLClassification": "Classifying the given comments as either toxic or not toxic",
210
+ "MalteseNewsClassification": "Categorizing the given news title",
211
+ "MultiEURLEXMultilabelClassification": "Categorizing the given news title",
212
+ "BrazilianToxicTweetsClassification": "Classifying the given comments as either toxic or not toxic",
213
+ "CTKFactsNLI": "Retrieve semantically similar text",
214
+ "indonli": "Retrieve semantically similar text",
215
+ "ArmenianParaphrasePC": "Retrieve semantically similar text",
216
+ "PawsXPairClassification": "Retrieve semantically similar text",
217
+ "RTE3": "Retrieve semantically similar text",
218
+ "XNLI": "Retrieve semantically similar text",
219
+ "PpcPC": "Retrieve semantically similar text",
220
+ "GermanSTSBenchmark": "Retrieve semantically similar text",
221
+ "SICK-R": "Retrieve semantically similar text",
222
+ "STS13": "Retrieve semantically similar text",
223
+ "STS14": "Retrieve semantically similar text",
224
+ "STSBenchmark": "Retrieve semantically similar text",
225
+ "FaroeseSTS": "Retrieve semantically similar text",
226
+ "FinParaSTS": "Retrieve semantically similar text",
227
+ "JSICK": "Retrieve semantically similar text",
228
+ "IndicCrosslingualSTS": "Retrieve semantically similar text",
229
+ "SemRel24STS": "Retrieve semantically similar text",
230
+ "STS17": "Retrieve semantically similar text",
231
+ "STS22.v2": "Retrieve semantically similar text",
232
+ "STSES": "Retrieve semantically similar text",
233
+ "STSB": "Retrieve semantically similar text",
234
+ "AILAStatutes": "Given a query, retrieve documents that answer the query.",
235
+ "HagridRetrieval": "Given a query, retrieve documents that answer the query.",
236
+ "LegalBenchCorporateLobbying": "Given a query, retrieve documents that answer the query.",
237
+ "LEMBPasskeyRetrieval": "Given a query, retrieve documents that answer the query.",
238
+ "BelebeleRetrieval": "Given a query, retrieve documents that answer the query.",
239
+ "MLQARetrieval": "Given a query, retrieve documents that answer the query.",
240
+ "StatcanDialogueDatasetRetrieval": "Given a query, retrieve documents that answer the query.",
241
+ "WikipediaRetrievalMultilingual": "Given a query, retrieve documents that answer the query.",
242
+ "Core17InstructionRetrieval": "Given a query, retrieve documents that answer the query.",
243
+ "News21InstructionRetrieval": "Given a query, retrieve documents that answer the query.",
244
+ "Robust04InstructionRetrieval": "Given a query, retrieve documents that answer the query.",
245
+ "WebLINXCandidatesReranking": "Given a query, retrieve documents that answer the query.",
246
+ "WikipediaRerankingMultilingual": "Given a query, retrieve documents that answer the query.",
247
+ "STS15": "Retrieve semantically similar text",
248
+ "MIRACLRetrievalHardNegatives": "Given a question, retrieve passages that answer the question",
249
+ "BIOSSES": "Retrieve semantically similar text",
250
+ "CQADupstackRetrieval": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
251
+ "CQADupstackGamingRetrieval": {
252
+ "query": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
253
+ "passage": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question"
254
+ },
255
+ "CQADupstackUnixRetrieval": {
256
+ "query": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question",
257
+ "passage": "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question"
258
+ },
259
+ "STS16": "Retrieve semantically similar text",
260
+ "SummEval": "Retrieve semantically similar text",
261
+ "ATEC": "Retrieve semantically similar text"
262
+ }
sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 512,
3
+ "do_lower_case": false
4
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "mask_token": {
25
+ "content": "<|mask|>",
26
+ "lstrip": true,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "pad_token": {
32
+ "content": "<|endoftext|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fed6809a51ebca45ce2df9ac10fc3aa4ed7f05c659dc09e96be7d814271c46b
3
+ size 11422913
tokenizer_config.json ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "151645": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "151646": {
31
+ "content": "<|object_ref_start|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|object_ref_end|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "151648": {
47
+ "content": "<|box_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "151649": {
55
+ "content": "<|box_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|mask|>",
168
+ "lstrip": true,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": true
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "151665": {
183
+ "content": "<tool_response>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "151666": {
191
+ "content": "</tool_response>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "151667": {
199
+ "content": "<think>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "151668": {
207
+ "content": "</think>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ }
214
+ },
215
+ "additional_special_tokens": [
216
+ "<|im_start|>",
217
+ "<|im_end|>",
218
+ "<|object_ref_start|>",
219
+ "<|object_ref_end|>",
220
+ "<|box_start|>",
221
+ "<|box_end|>",
222
+ "<|quad_start|>",
223
+ "<|quad_end|>",
224
+ "<|vision_start|>",
225
+ "<|vision_end|>",
226
+ "<|vision_pad|>",
227
+ "<|image_pad|>",
228
+ "<|video_pad|>"
229
+ ],
230
+ "bos_token": null,
231
+ "clean_up_tokenization_spaces": false,
232
+ "eos_token": "<|endoftext|>",
233
+ "errors": "replace",
234
+ "extra_special_tokens": {},
235
+ "mask_token": "<|mask|>",
236
+ "model_max_length": 131072,
237
+ "pad_token": "<|endoftext|>",
238
+ "split_special_tokens": false,
239
+ "tokenizer_class": "Qwen2Tokenizer",
240
+ "unk_token": null
241
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff