TheoDB commited on
Commit
9db6b2b
·
verified ·
1 Parent(s): da0547a

Upload BidirLM-270M-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": 640,
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-270M-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-270M
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 32,768 context length (Gemma3). 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-270M", 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-270M", trust_remote_code=True)
160
+
161
+ # Sequence classification (e.g., NLI: entailment, neutral, contradiction)
162
+ seq_model = AutoModelForSequenceClassification.from_pretrained(
163
+ "BidirLM/BidirLM-270M",
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-270M",
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 140 languages, inherited from the Gemma3 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-270M and BidirLM-270M-Base?
210
+
211
+ [BidirLM/BidirLM-270M-Base](https://huggingface.co/BidirLM/BidirLM-270M-Base) is the intermediate MNTP-adapted checkpoint (bidirectional pretraining stage). BidirLM-270M 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,4 @@
 
 
 
 
 
1
+ {
2
+ "<image_soft_token>": 262144,
3
+ "<|mask|>": 262145
4
+ }
config.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_sliding_window_pattern": 6,
3
+ "architectures": [
4
+ "BidirLMModel"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "attn_logit_softcapping": null,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_bidirlm.BidirLMConfig",
11
+ "AutoModel": "modeling_bidirlm.BidirLMModel",
12
+ "AutoModelForMaskedLM": "modeling_bidirlm.BidirLMForMaskedLM",
13
+ "AutoModelForPreTraining": "modeling_bidirlm.BidirLMPreTrainedModel",
14
+ "AutoModelForSequenceClassification": "modeling_bidirlm.BidirLMForSequenceClassification",
15
+ "AutoModelForTokenClassification": "modeling_bidirlm.BidirLMForTokenClassification"
16
+ },
17
+ "bos_token_id": 2,
18
+ "classifier_pooling": "late",
19
+ "dtype": "bfloat16",
20
+ "eos_token_id": 1,
21
+ "final_logit_softcapping": null,
22
+ "head_dim": 256,
23
+ "hidden_activation": "gelu_pytorch_tanh",
24
+ "hidden_size": 640,
25
+ "initializer_range": 0.02,
26
+ "intermediate_size": 2048,
27
+ "layer_types": [
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "sliding_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "sliding_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "sliding_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention"
46
+ ],
47
+ "max_position_embeddings": 32768,
48
+ "model_type": "bidirlm",
49
+ "num_attention_heads": 4,
50
+ "num_hidden_layers": 18,
51
+ "num_key_value_heads": 1,
52
+ "pad_token_id": 1,
53
+ "query_pre_attn_scalar": 256,
54
+ "rms_norm_eps": 1e-06,
55
+ "rope_local_base_freq": 10000.0,
56
+ "rope_scaling": null,
57
+ "rope_theta": 1000000.0,
58
+ "sliding_window": 256,
59
+ "transformers_version": "4.57.6",
60
+ "use_bidirectional_attention": true,
61
+ "use_cache": true,
62
+ "vocab_size": 262144
63
+ }
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,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma3/modular_gemma3.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Any, Optional, Union
23
+
24
+ import transformers
25
+ _v = transformers.__version__
26
+ if _v < "4.57.6" or _v >= "5.0.0":
27
+ raise ImportError(
28
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
29
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
30
+ )
31
+
32
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
33
+ from transformers.modeling_rope_utils import rope_config_validation
34
+ from transformers.utils import logging
35
+ from transformers.models.siglip import SiglipVisionConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ class BidirLMConfig(PretrainedConfig):
42
+ r"""
43
+ This is the configuration class to store the configuration of a [`BidirLMModel`]. It is used to instantiate an Gemma3Text
44
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
45
+ defaults will yield a similar configuration to that of the Gemma3Text-7B.
46
+ e.g. [google/gemma3_text-7b](https://huggingface.co/google/gemma3_text-7b)
47
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
48
+ documentation from [`PretrainedConfig`] for more information.
49
+ Args:
50
+ vocab_size (`int`, *optional*, defaults to 262208):
51
+ Vocabulary size of the Gemma3Text model. Defines the number of different tokens that can be represented by the
52
+ `inputs_ids` passed when calling [`BidirLMModel`]
53
+ hidden_size (`int`, *optional*, defaults to 2304):
54
+ Dimension of the hidden representations.
55
+ intermediate_size (`int`, *optional*, defaults to 9216):
56
+ Dimension of the MLP representations.
57
+ num_hidden_layers (`int`, *optional*, defaults to 26):
58
+ Number of hidden layers in the Transformer decoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer decoder.
61
+ num_key_value_heads (`int`, *optional*, defaults to 4):
62
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
63
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
64
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
65
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
66
+ by meanpooling all the original heads within that group. For more details, check out [this
67
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
68
+ `num_attention_heads`.
69
+ head_dim (`int`, *optional*, defaults to 256):
70
+ The attention head dimension.
71
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
72
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
73
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
74
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
75
+ The maximum sequence length that this model might ever be used with.
76
+ initializer_range (`float`, *optional*, defaults to 0.02):
77
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
78
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
79
+ The epsilon used by the rms normalization layers.
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
82
+ relevant if `config.is_decoder=True`.
83
+ pad_token_id (`int`, *optional*, defaults to 0):
84
+ Padding token id.
85
+ eos_token_id (`int`, *optional*, defaults to 1):
86
+ End of stream token id.
87
+ bos_token_id (`int`, *optional*, defaults to 2):
88
+ Beginning of stream token id.
89
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
90
+ Whether to tie weight embeddings
91
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
92
+ The base period of the RoPE embeddings.
93
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
94
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
95
+ attention_dropout (`float`, *optional*, defaults to 0.0):
96
+ The dropout ratio for the attention probabilities.
97
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
98
+ Scaling factor used on the attention scores
99
+ sliding_window (`int`, *optional*, defaults to 4096):
100
+ In Gemma3Text, every other layer uses sliding window attention. This is the size of the sliding window.
101
+ layer_types (`list`, *optional*):
102
+ Attention pattern for each layer.
103
+ final_logit_softcapping (`float`, *optional*):
104
+ Scaling factor when applying tanh softcapping on the logits.
105
+ attn_logit_softcapping (`float`, *optional*):
106
+ Scaling factor when applying tanh softcapping on the attention scores.
107
+ rope_scaling (`Dict`, *optional*):
108
+ Dictionary containing the scaling configuration for the RoPE embeddings used in global attention. NOTE: if you apply new rope type
109
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
110
+ accordingly.
111
+ Expected contents:
112
+ `rope_type` (`str`):
113
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
114
+ 'llama3'], with 'default' being the original RoPE implementation.
115
+ `factor` (`float`, *optional*):
116
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
117
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
118
+ original maximum pre-trained length.
119
+ `original_max_position_embeddings` (`int`, *optional*):
120
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
121
+ pretraining.
122
+ `attention_factor` (`float`, *optional*):
123
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
124
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
125
+ `factor` field to infer the suggested value.
126
+ `beta_fast` (`float`, *optional*):
127
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
128
+ ramp function. If unspecified, it defaults to 32.
129
+ `beta_slow` (`float`, *optional*):
130
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
131
+ ramp function. If unspecified, it defaults to 1.
132
+ `short_factor` (`list[float]`, *optional*):
133
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
134
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
135
+ size divided by the number of attention heads divided by 2
136
+ `long_factor` (`list[float]`, *optional*):
137
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
138
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
139
+ size divided by the number of attention heads divided by 2
140
+ `low_freq_factor` (`float`, *optional*):
141
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
142
+ `high_freq_factor` (`float`, *optional*):
143
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
144
+ rope_local_base_freq (float, *optional*, defaults to 10000.0):
145
+ The base period of the RoPE embeddings for local attention.
146
+ use_bidirectional_attention (`bool`, *optional*, defaults to `False`): If True, the model will attend to all
147
+ text tokens instead of using a causal mask. This does not change behavior for vision tokens.
148
+
149
+ ```python
150
+ >>> from transformers import BidirLMModel, BidirLMConfig
151
+ >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
152
+ >>> configuration = BidirLMConfig()
153
+ >>> # Initializing a model from the gemma3_text-7b style configuration
154
+ >>> model = BidirLMModel(configuration)
155
+ >>> # Accessing the model configuration
156
+ >>> configuration = model.config
157
+ ```
158
+ """
159
+
160
+ model_type = "bidirlm"
161
+ keys_to_ignore_at_inference = ["past_key_values"]
162
+ base_model_tp_plan = {
163
+ "layers.*.self_attn.q_proj": "colwise",
164
+ "layers.*.self_attn.k_proj": "colwise",
165
+ "layers.*.self_attn.v_proj": "colwise",
166
+ "layers.*.self_attn.o_proj": "rowwise",
167
+ "layers.*.mlp.gate_proj": "colwise",
168
+ "layers.*.mlp.up_proj": "colwise",
169
+ "layers.*.mlp.down_proj": "rowwise",
170
+ }
171
+ base_model_pp_plan = {
172
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
173
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
174
+ "norm": (["hidden_states"], ["hidden_states"]),
175
+ }
176
+
177
+ def __init__(
178
+ self,
179
+ vocab_size=262_208,
180
+ hidden_size=2304,
181
+ intermediate_size=9216,
182
+ num_hidden_layers=26,
183
+ num_attention_heads=8,
184
+ num_key_value_heads=4,
185
+ head_dim=256,
186
+ hidden_activation="gelu_pytorch_tanh",
187
+ max_position_embeddings=131_072,
188
+ initializer_range=0.02,
189
+ rms_norm_eps=1e-6,
190
+ use_cache=True,
191
+ pad_token_id=0,
192
+ eos_token_id=1,
193
+ bos_token_id=2,
194
+ tie_word_embeddings=True,
195
+ rope_theta=1_000_000.0,
196
+ attention_bias=False,
197
+ attention_dropout=0.0,
198
+ query_pre_attn_scalar=256,
199
+ sliding_window=4096,
200
+ layer_types=None,
201
+ final_logit_softcapping=None,
202
+ attn_logit_softcapping=None,
203
+ rope_scaling=None,
204
+ rope_local_base_freq=10_000.0,
205
+ use_bidirectional_attention=True,
206
+ classifier_pooling="late",
207
+ **kwargs,
208
+ ):
209
+ super().__init__(
210
+ pad_token_id=pad_token_id,
211
+ bos_token_id=bos_token_id,
212
+ eos_token_id=eos_token_id,
213
+ tie_word_embeddings=tie_word_embeddings,
214
+ **kwargs,
215
+ )
216
+ self.vocab_size = vocab_size
217
+ self.max_position_embeddings = max_position_embeddings
218
+ self.hidden_size = hidden_size
219
+ self.intermediate_size = intermediate_size
220
+ self.num_hidden_layers = num_hidden_layers
221
+ self.num_attention_heads = num_attention_heads
222
+ self.head_dim = head_dim
223
+ self.num_key_value_heads = num_key_value_heads
224
+ self.initializer_range = initializer_range
225
+ self.rms_norm_eps = rms_norm_eps
226
+ self.use_cache = use_cache
227
+ self.rope_theta = rope_theta
228
+ self.attention_bias = attention_bias
229
+ self.attention_dropout = attention_dropout
230
+ self.hidden_activation = hidden_activation
231
+ self.query_pre_attn_scalar = query_pre_attn_scalar
232
+ self.sliding_window = sliding_window
233
+ self.final_logit_softcapping = final_logit_softcapping
234
+ self.attn_logit_softcapping = attn_logit_softcapping
235
+ self.layer_types = layer_types
236
+ self.use_bidirectional_attention = use_bidirectional_attention
237
+ self.classifier_pooling = classifier_pooling
238
+ if use_bidirectional_attention:
239
+ self.sliding_window = self.sliding_window // 2
240
+
241
+ self.rope_local_base_freq = rope_local_base_freq
242
+ self.rope_scaling = rope_scaling
243
+ rope_config_validation(self)
244
+
245
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
246
+ self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
247
+
248
+ if self.layer_types is None:
249
+ self.layer_types = [
250
+ "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
251
+ for i in range(self.num_hidden_layers)
252
+ ]
253
+ layer_type_validation(self.layer_types, self.num_hidden_layers)
254
+
255
+
256
+ class Gemma3Config(PretrainedConfig):
257
+ r"""
258
+ This is the configuration class to store the configuration of a [`Gemma3ForConditionalGeneration`]. It is used to instantiate an
259
+ Gemma3ForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration
260
+ with the defaults will yield a similar configuration to that of the PaliGemma-2B.
261
+
262
+ e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b)
263
+
264
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
265
+ documentation from [`PretrainedConfig`] for more information.
266
+
267
+ Args:
268
+ text_config (`Union[BidirLMConfig, dict]`, *optional*):
269
+ The config object of the text backbone.
270
+ vision_config (`Union[AutoConfig, dict]`, *optional*):
271
+ Custom vision config or dict.
272
+ mm_tokens_per_image (`int`, *optional*, defaults to 256):
273
+ The number of tokens per image embedding.
274
+ boi_token_index (`int`, *optional*, defaults to 255999):
275
+ The begin-of-image token index to wrap the image prompt.
276
+ eoi_token_index (`int`, *optional*, defaults to 256000):
277
+ The end-of-image token index to wrap the image prompt.
278
+ image_token_index (`int`, *optional*, defaults to 262144):
279
+ The image token index to encode the image prompt.
280
+ initializer_range (`float`, *optional*, defaults to 0.02):
281
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
282
+
283
+
284
+ Example:
285
+
286
+ ```python
287
+ >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, BidirLMConfig
288
+
289
+ >>> # Initializing a Siglip-like vision config
290
+ >>> vision_config = SiglipVisionConfig()
291
+
292
+ >>> # Initializing a Gemma3 Text config
293
+ >>> text_config = BidirLMConfig()
294
+
295
+ >>> # Initializing a Gemma3 gemma-3-4b style configuration
296
+ >>> configuration = Gemma3Config(vision_config, text_config)
297
+
298
+ >>> # Initializing a model from the gemma-3-4b style configuration
299
+ >>> model = BidirLMConfig(configuration)
300
+
301
+ >>> # Accessing the model configuration
302
+ >>> configuration = model.config
303
+ ```"""
304
+
305
+ model_type = "bidirlm"
306
+ attribute_map = {
307
+ "image_token_id": "image_token_index",
308
+ "boi_token_id": "boi_token_index",
309
+ "eoi_token_id": "eoi_token_index",
310
+ }
311
+ sub_configs = {
312
+ "text_config": BidirLMConfig,
313
+ "vision_config": SiglipVisionConfig,
314
+ }
315
+
316
+ def __init__(
317
+ self,
318
+ text_config: Optional[Union[BidirLMConfig, dict[str, Any]]] = None,
319
+ vision_config: Optional[Union[SiglipVisionConfig, dict[str, Any]]] = None,
320
+ mm_tokens_per_image: int = 256,
321
+ boi_token_index: int = 255_999,
322
+ eoi_token_index: int = 256_000,
323
+ image_token_index: int = 262_144,
324
+ initializer_range: float = 0.02,
325
+ **kwargs,
326
+ ):
327
+ if text_config is None:
328
+ text_config = BidirLMConfig()
329
+ logger.info("text_config is None, using default BidirLMConfig text config.")
330
+ elif isinstance(text_config, dict):
331
+ text_config = BidirLMConfig(**text_config)
332
+
333
+ if isinstance(vision_config, dict):
334
+ vision_config = SiglipVisionConfig(**vision_config)
335
+ elif vision_config is None:
336
+ vision_config = SiglipVisionConfig()
337
+ logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
338
+
339
+ self.text_config = text_config
340
+ self.vision_config = vision_config
341
+ self.mm_tokens_per_image = mm_tokens_per_image
342
+ self.boi_token_index = boi_token_index
343
+ self.eoi_token_index = eoi_token_index
344
+ self.image_token_index = image_token_index
345
+ self.initializer_range = initializer_range
346
+
347
+ super().__init__(**kwargs)
348
+
349
+
350
+ __all__ = ["Gemma3Config", "BidirLMConfig"]
final_results.png ADDED

Git LFS Details

  • SHA256: 165257135cb40c3b9e7dcec94d225a0cce3a5c12f9ef0d152972eec048d0493a
  • Pointer size: 131 Bytes
  • Size of remote file: 738 kB
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0aef481eadb6976ce447ba178d005e49f4060d907759194cb4fc27380e42e06
3
+ size 536221640
modeling_bidirlm.py ADDED
@@ -0,0 +1,1142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional
3
+
4
+ import transformers
5
+ _v = transformers.__version__
6
+ if _v < "4.57.6" or _v >= "5.0.0":
7
+ raise ImportError(
8
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
9
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
10
+ )
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_layers import GradientCheckpointingLayer
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutput,
19
+ MaskedLMOutput,
20
+ SequenceClassifierOutput,
21
+ TokenClassifierOutput,
22
+ )
23
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
24
+ from transformers.modeling_utils import PreTrainedModel
25
+
26
+ from .configuration_bidirlm import Gemma3Config, BidirLMConfig
27
+
28
+ try:
29
+ import flash_attn
30
+
31
+ FLASH_ATTN_AVAILABLE = True
32
+ except ImportError:
33
+ FLASH_ATTN_AVAILABLE = False
34
+
35
+
36
+ def batch_input_to_cu_seqlens(x: torch.Tensor, attention_mask: torch.Tensor):
37
+ lengths = attention_mask.sum(dim=1)
38
+ max_seqlen = int(lengths.max().item())
39
+ cu_seqlens = torch.zeros(lengths.size(0) + 1, dtype=torch.int32, device=x.device)
40
+ cu_seqlens[1:] = torch.cumsum(lengths, dim=0)
41
+ x = x[attention_mask.bool()]
42
+ return x, cu_seqlens, max_seqlen
43
+
44
+
45
+ def cu_seqlens_to_batch_input(
46
+ x: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int
47
+ ):
48
+ B = cu_seqlens.size(0) - 1
49
+ D = x.size(1)
50
+ idx = torch.arange(max_seqlen, device=x.device).expand(B, max_seqlen)
51
+ lens = (cu_seqlens[1:] - cu_seqlens[:-1]).unsqueeze(1)
52
+ mask = idx < lens
53
+ base = cu_seqlens[:-1].unsqueeze(1)
54
+ gather_idx = (idx + base) * mask
55
+ out = torch.zeros(B, max_seqlen, D, device=x.device, dtype=x.dtype)
56
+ out[mask] = x[gather_idx[mask]]
57
+ return out
58
+
59
+
60
+ def cu_attention_weight_to_batch(hidden_states, cu_seqlens, max_seqlen):
61
+ H, T, _ = hidden_states.shape
62
+ device = hidden_states.device
63
+ cu_seqlens = cu_seqlens.to(device, dtype=torch.long)
64
+
65
+ B = cu_seqlens.numel() - 1
66
+ start = cu_seqlens[:-1]
67
+ end = cu_seqlens[1:]
68
+ L = end - start
69
+
70
+ p = torch.arange(max_seqlen, device=device)
71
+ valid = p.unsqueeze(0) < L.unsqueeze(1)
72
+
73
+ rel = p.unsqueeze(0)
74
+ abs_idx = start.unsqueeze(1) + rel
75
+ abs_idx = torch.where(valid, abs_idx, torch.zeros_like(abs_idx))
76
+
77
+ attn = hidden_states.unsqueeze(0).expand(B, -1, -1, -1)
78
+
79
+ row_index = abs_idx[:, None, :, None].expand(B, H, max_seqlen, T)
80
+ attn_rows = torch.gather(attn, dim=2, index=row_index)
81
+
82
+ col_index = abs_idx[:, None, None, :].expand(B, H, max_seqlen, max_seqlen)
83
+ attn_padded = torch.gather(attn_rows, dim=3, index=col_index)
84
+
85
+ mask = valid.to(attn_padded.dtype)
86
+ attn_padded = attn_padded * mask[:, None, :, None] * mask[:, None, None, :]
87
+
88
+ return attn_padded
89
+
90
+
91
+ class Gemma3Attention(nn.Module):
92
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
93
+
94
+ def __init__(self, config: BidirLMConfig, layer_idx: int):
95
+ super().__init__()
96
+ self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
97
+ self.config = config
98
+ self.layer_idx = layer_idx
99
+ self.head_dim = getattr(
100
+ config, "head_dim", config.hidden_size // config.num_attention_heads
101
+ )
102
+ self.num_key_value_groups = (
103
+ config.num_attention_heads // config.num_key_value_heads
104
+ )
105
+ self.scaling = config.query_pre_attn_scalar**-0.5
106
+ self.attention_dropout = self.config.attention_dropout
107
+
108
+ self.q_proj = nn.Linear(
109
+ config.hidden_size,
110
+ config.num_attention_heads * self.head_dim,
111
+ bias=config.attention_bias,
112
+ )
113
+ self.k_proj = nn.Linear(
114
+ config.hidden_size,
115
+ config.num_key_value_heads * self.head_dim,
116
+ bias=config.attention_bias,
117
+ )
118
+ self.v_proj = nn.Linear(
119
+ config.hidden_size,
120
+ config.num_key_value_heads * self.head_dim,
121
+ bias=config.attention_bias,
122
+ )
123
+ self.o_proj = nn.Linear(
124
+ config.num_attention_heads * self.head_dim,
125
+ config.hidden_size,
126
+ bias=config.attention_bias,
127
+ )
128
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
129
+ self.sliding_window = config.sliding_window if self.is_sliding else None
130
+
131
+ self.q_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
132
+ self.k_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
133
+
134
+ def forward(
135
+ self,
136
+ hidden_states,
137
+ position_embeddings,
138
+ attention_mask,
139
+ cu_seqlens: Optional[torch.Tensor],
140
+ max_seqlen: Optional[int],
141
+ window_size: Optional[tuple[int, int]] = None,
142
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
143
+ input_shape = hidden_states.shape[:-1]
144
+ hidden_shape = (*input_shape, -1, self.head_dim)
145
+
146
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(0, 1)
147
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(0, 1)
148
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(0, 1)
149
+
150
+ query_states = self.q_norm(query_states)
151
+ key_states = self.k_norm(key_states)
152
+
153
+ cos, sin = position_embeddings
154
+ query_states, key_states = apply_rotary_pos_emb(
155
+ query_states, key_states, cos, sin
156
+ )
157
+
158
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
159
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
160
+
161
+ if (
162
+ self.config._attn_implementation == "flash_attention_2"
163
+ and FLASH_ATTN_AVAILABLE
164
+ ):
165
+ attn_weights = None
166
+ attn_output = flash_attn.flash_attn_varlen_func(
167
+ query_states.transpose(0, 1),
168
+ key_states.transpose(0, 1),
169
+ value_states.transpose(0, 1),
170
+ cu_seqlens,
171
+ cu_seqlens,
172
+ max_seqlen_q=max_seqlen,
173
+ max_seqlen_k=max_seqlen,
174
+ dropout_p=self.attention_dropout if self.training else 0.0,
175
+ softmax_scale=self.scaling,
176
+ causal=not self.config.use_bidirectional_attention,
177
+ window_size=window_size,
178
+ )
179
+ else:
180
+ attn_output, attn_weights = sdpa_attention_forward(
181
+ query_states,
182
+ key_states,
183
+ value_states,
184
+ attention_mask=attention_mask,
185
+ scaling=self.scaling,
186
+ dropout=self.attention_dropout if self.training else 0.0,
187
+ softcap=self.attn_logit_softcapping,
188
+ )
189
+
190
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
191
+ attn_output = self.o_proj(attn_output)
192
+ return attn_output, attn_weights
193
+
194
+
195
+ def sdpa_attention_forward(
196
+ q,
197
+ k,
198
+ v,
199
+ attention_mask,
200
+ scaling,
201
+ dropout: float = 0.0,
202
+ softcap: Optional[float] = None,
203
+ ):
204
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) * scaling
205
+
206
+ if softcap is not None:
207
+ attn_weights = attn_weights / softcap
208
+ attn_weights = torch.tanh(attn_weights)
209
+ attn_weights = attn_weights * softcap
210
+
211
+ attn_weights = attn_weights + attention_mask
212
+
213
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
214
+ q.dtype
215
+ )
216
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout)
217
+
218
+ attn_output = torch.matmul(attn_weights, v)
219
+ attn_output = attn_output.transpose(0, 1).contiguous()
220
+
221
+ return attn_output, attn_weights
222
+
223
+
224
+ def create_packed_seqs_mask(
225
+ cu_seqlens: torch.Tensor,
226
+ causal: bool = True,
227
+ device: torch.device = torch.device("cpu"),
228
+ window_size: Optional[tuple[int, int]] = None,
229
+ ) -> torch.Tensor:
230
+ """
231
+ Builds a block-diagonal attention mask for packed sequences.
232
+ Returns shape [total_len, total_len] with 0.0 for attention and -inf for masked.
233
+ """
234
+ total_len = cu_seqlens[-1]
235
+ seq_lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).to(device)
236
+
237
+ seq_ids = torch.repeat_interleave(
238
+ torch.arange(len(seq_lengths), device=device),
239
+ seq_lengths
240
+ )
241
+
242
+ mask = seq_ids.unsqueeze(0) == seq_ids.unsqueeze(1)
243
+
244
+ if causal:
245
+ mask &= torch.tril(torch.ones(total_len, total_len, device=device, dtype=torch.bool))
246
+
247
+ if window_size is not None:
248
+ left, right = window_size
249
+ start_indices = torch.repeat_interleave(cu_seqlens[:-1].to(device), seq_lengths)
250
+ relative_pos = torch.arange(total_len, device=device) - start_indices
251
+
252
+ distance = relative_pos.unsqueeze(0) - relative_pos.unsqueeze(1)
253
+
254
+ if left >= 0:
255
+ mask &= (distance >= -left)
256
+ if right >= 0:
257
+ mask &= (distance <= right)
258
+
259
+ attn_mask = torch.full((total_len, total_len), float('-inf'), device=device)
260
+ attn_mask.masked_fill_(mask, 0.0)
261
+
262
+ return attn_mask
263
+
264
+
265
+ class Gemma3EncoderLayer(GradientCheckpointingLayer):
266
+ def __init__(self, config: BidirLMConfig, layer_idx: int):
267
+ super().__init__()
268
+ self.config = config
269
+ self.hidden_size = config.hidden_size
270
+ self.layer_idx = layer_idx
271
+ self.attention_type = config.layer_types[layer_idx]
272
+ self.self_attn = Gemma3Attention(config=config, layer_idx=layer_idx)
273
+ self.mlp = Gemma3MLP(config)
274
+ self.input_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
275
+ self.post_attention_layernorm = Gemma3RMSNorm(
276
+ self.hidden_size, eps=config.rms_norm_eps
277
+ )
278
+ self.pre_feedforward_layernorm = Gemma3RMSNorm(
279
+ self.hidden_size, eps=config.rms_norm_eps
280
+ )
281
+ self.post_feedforward_layernorm = Gemma3RMSNorm(
282
+ self.hidden_size, eps=config.rms_norm_eps
283
+ )
284
+
285
+ def forward(
286
+ self,
287
+ hidden_states: torch.Tensor,
288
+ position_embeddings_global: torch.Tensor,
289
+ position_embeddings_local: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ cu_seqlens: Optional[torch.Tensor] = None,
292
+ max_seqlen: Optional[int] = None,
293
+ window_size: Optional[tuple[int, int]] = None,
294
+ output_attentions: Optional[bool] = False,
295
+ ) -> tuple[
296
+ torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]
297
+ ]:
298
+ residual = hidden_states
299
+ hidden_states = self.input_layernorm(hidden_states)
300
+
301
+ if self.self_attn.is_sliding:
302
+ position_embeddings = position_embeddings_local
303
+ else:
304
+ position_embeddings = position_embeddings_global
305
+
306
+ hidden_states, self_attn_weights = self.self_attn(
307
+ hidden_states=hidden_states,
308
+ position_embeddings=position_embeddings,
309
+ attention_mask=attention_mask,
310
+ cu_seqlens=cu_seqlens,
311
+ max_seqlen=max_seqlen,
312
+ window_size=window_size,
313
+ )
314
+ hidden_states = self.post_attention_layernorm(hidden_states)
315
+ hidden_states = residual + hidden_states
316
+
317
+ residual = hidden_states
318
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
319
+ hidden_states = self.mlp(hidden_states)
320
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
321
+ hidden_states = residual + hidden_states
322
+
323
+ outputs = (hidden_states,)
324
+ if output_attentions:
325
+ outputs += (self_attn_weights,)
326
+
327
+ return outputs
328
+
329
+
330
+ class BidirLMPreTrainedModel(PreTrainedModel):
331
+ config: Gemma3Config
332
+ base_model_prefix = "model"
333
+ _supports_flash_attn = True
334
+
335
+ def _init_weights(self, module):
336
+ super()._init_weights(module)
337
+ # if isinstance(module, Gemma3MultiModalProjector):
338
+ # module.mm_input_projection_weight.data.zero_()
339
+ # # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
340
+ # elif "RMSNorm" in module.__class__.__name__:
341
+ # module.weight.data.zero_()
342
+ if "RMSNorm" in module.__class__.__name__:
343
+ module.weight.data.zero_()
344
+
345
+
346
+ class Gemma3TextScaledWordEmbedding(nn.Embedding):
347
+ """
348
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ num_embeddings: int,
354
+ embedding_dim: int,
355
+ padding_idx: int,
356
+ embed_scale: float = 1.0,
357
+ ):
358
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
359
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
360
+
361
+ def forward(self, input_ids: torch.Tensor):
362
+ return self.weight[input_ids, :] * self.embed_scale.to(self.weight.dtype)
363
+
364
+
365
+ class Gemma3MLP(nn.Module):
366
+ def __init__(self, config: BidirLMConfig):
367
+ super().__init__()
368
+ self.config = config
369
+ self.hidden_size = config.hidden_size
370
+ self.intermediate_size = config.intermediate_size
371
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
372
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
373
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
374
+ self.act_fn = ACT2FN[config.hidden_activation]
375
+
376
+ def forward(self, x):
377
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
378
+ return down_proj
379
+
380
+
381
+ class Gemma3RMSNorm(nn.Module):
382
+ def __init__(self, dim: int, eps: float = 1e-6):
383
+ super().__init__()
384
+ self.eps = eps
385
+ self.weight = nn.Parameter(torch.zeros(dim))
386
+
387
+ def _norm(self, x):
388
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
389
+
390
+ def forward(self, x):
391
+ output = self._norm(x.float())
392
+ # Llama does x.to(float16) * w whilst Gemma3 is (x * w).to(float16)
393
+ # See https://github.com/huggingface/transformers/pull/29402
394
+ output = output * (1.0 + self.weight.float())
395
+ return output.type_as(x)
396
+
397
+ def extra_repr(self):
398
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
399
+
400
+
401
+ class Gemma3RotaryEmbedding(nn.Module):
402
+ def __init__(self, config: BidirLMConfig, device=None):
403
+ super().__init__()
404
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
405
+ self.rope_type = config.rope_scaling.get(
406
+ "rope_type", config.rope_scaling.get("type")
407
+ )
408
+ else:
409
+ self.rope_type = "default"
410
+ self.max_seq_len_cached = config.max_position_embeddings
411
+ self.original_max_seq_len = config.max_position_embeddings
412
+
413
+ self.config = config
414
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
415
+
416
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
417
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
418
+ self.original_inv_freq = self.inv_freq
419
+
420
+ @torch.no_grad()
421
+ @dynamic_rope_update
422
+ def forward(self, x, position_ids):
423
+ inv_freq_expanded = self.inv_freq[:, None].float().to(x.device)
424
+ position_ids_expanded = position_ids[None, :].float()
425
+
426
+ device_type = (
427
+ x.device.type
428
+ if isinstance(x.device.type, str) and x.device.type != "mps"
429
+ else "cpu"
430
+ )
431
+ with torch.autocast(device_type=device_type, enabled=False):
432
+ freqs = (
433
+ inv_freq_expanded.float() @ position_ids_expanded.float()
434
+ ).transpose(0, 1)
435
+ emb = torch.cat((freqs, freqs), dim=-1)
436
+ cos = emb.cos() * self.attention_scaling
437
+ sin = emb.sin() * self.attention_scaling
438
+
439
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
440
+
441
+
442
+ def rotate_half(x):
443
+ """Rotates half the hidden dims of the input."""
444
+ x1 = x[..., : x.shape[-1] // 2]
445
+ x2 = x[..., x.shape[-1] // 2 :]
446
+ return torch.cat((-x2, x1), dim=-1)
447
+
448
+
449
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=0):
450
+ """Applies Rotary Position Embedding to the query and key tensors.
451
+
452
+ Args:
453
+ q (`torch.Tensor`): The query tensor.
454
+ k (`torch.Tensor`): The key tensor.
455
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
456
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
457
+ position_ids (`torch.Tensor`, *optional*):
458
+ Deprecated and unused.
459
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
460
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
461
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
462
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
463
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
464
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
465
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
466
+ Returns:
467
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
468
+ """
469
+ cos = cos.unsqueeze(unsqueeze_dim)
470
+ sin = sin.unsqueeze(unsqueeze_dim)
471
+ q_embed = (q * cos) + (rotate_half(q) * sin)
472
+ k_embed = (k * cos) + (rotate_half(k) * sin)
473
+ return q_embed, k_embed
474
+
475
+
476
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
477
+ """
478
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
479
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
480
+ """
481
+ num_key_value_heads, slen, head_dim = hidden_states.shape
482
+ if n_rep == 1:
483
+ return hidden_states
484
+ hidden_states = hidden_states[:, None, :, :].expand(
485
+ num_key_value_heads, n_rep, slen, head_dim
486
+ )
487
+ return hidden_states.reshape(num_key_value_heads * n_rep, slen, head_dim)
488
+
489
+
490
+ class BidirLMModel(BidirLMPreTrainedModel):
491
+ config: BidirLMConfig
492
+
493
+ def __init__(self, config: BidirLMConfig):
494
+ super().__init__(config)
495
+ self.padding_idx = config.pad_token_id
496
+ self.vocab_size = config.vocab_size
497
+
498
+ self.embed_tokens = Gemma3TextScaledWordEmbedding(
499
+ config.vocab_size,
500
+ config.hidden_size,
501
+ self.padding_idx,
502
+ embed_scale=self.config.hidden_size**0.5,
503
+ )
504
+ self.layers = nn.ModuleList(
505
+ [
506
+ Gemma3EncoderLayer(config, layer_idx)
507
+ for layer_idx in range(config.num_hidden_layers)
508
+ ]
509
+ )
510
+ self.norm = Gemma3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
511
+ self.rotary_emb = Gemma3RotaryEmbedding(config=config)
512
+ self.gradient_checkpointing = False
513
+
514
+ config = copy.deepcopy(config)
515
+ config.rope_theta = config.rope_local_base_freq
516
+ config.rope_scaling = {"rope_type": "default"}
517
+ self.rotary_emb_local = Gemma3RotaryEmbedding(config=config)
518
+
519
+ self.post_init()
520
+
521
+ def forward(
522
+ self,
523
+ input_ids: torch.LongTensor,
524
+ attention_mask: Optional[torch.Tensor] = None,
525
+ *,
526
+ cu_seqlens: Optional[torch.Tensor] = None,
527
+ max_seqlen: Optional[int] = None,
528
+ output_attentions: Optional[bool] = None,
529
+ output_hidden_states: Optional[bool] = None,
530
+ return_dict: Optional[bool] = None,
531
+ **kwargs,
532
+ ) -> tuple[torch.Tensor] | BaseModelOutput:
533
+ output_attentions = (
534
+ output_attentions
535
+ if output_attentions is not None
536
+ else self.config.output_attentions
537
+ )
538
+ output_hidden_states = (
539
+ output_hidden_states
540
+ if output_hidden_states is not None
541
+ else self.config.output_hidden_states
542
+ )
543
+ return_dict = (
544
+ return_dict if return_dict is not None else self.config.use_return_dict
545
+ )
546
+ all_hidden_states = () if output_hidden_states else None
547
+ all_self_attns = () if output_attentions else None
548
+
549
+ # For MNTP XP
550
+ batch_size, seq_len = input_ids.size()
551
+ new_input_ids = torch.empty((batch_size, seq_len + 1), dtype=input_ids.dtype, device=input_ids.device)
552
+ new_input_ids[:, 0] = 2
553
+ new_input_ids[:, 1:] = input_ids
554
+
555
+ if attention_mask is not None:
556
+ new_attention_mask = torch.empty((batch_size, seq_len + 1), dtype=attention_mask.dtype, device=attention_mask.device)
557
+ new_attention_mask[:, 0] = 1
558
+ new_attention_mask[:, 1:] = attention_mask
559
+ attention_mask = new_attention_mask
560
+ input_ids, cu_seqlens, max_seqlen = batch_input_to_cu_seqlens(new_input_ids, attention_mask)
561
+ else:
562
+ input_ids = new_input_ids
563
+
564
+ if cu_seqlens is None or max_seqlen is None:
565
+ cu_seqlens = torch.tensor(
566
+ [0, input_ids.size(0)], dtype=torch.int32, device=input_ids.device
567
+ )
568
+ max_seqlen = input_ids.size(0)
569
+
570
+ hidden_states = self.embed_tokens(input_ids)
571
+
572
+ position_ids = torch.arange(len(input_ids), device=hidden_states.device)
573
+ position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
574
+ position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
575
+
576
+ window_size = (
577
+ (
578
+ self.config.sliding_window,
579
+ self.config.sliding_window if self.config.use_bidirectional_attention else 0
580
+ )
581
+ if self.config.sliding_window is not None
582
+ else None
583
+ )
584
+ # Only create attention masks when NOT using flash attention
585
+ # Flash attention handles masking internally and doesn't need pre-computed masks
586
+ if self.config._attn_implementation == "flash_attention_2" and FLASH_ATTN_AVAILABLE:
587
+ mask_mapping = {
588
+ "full_attention": None,
589
+ "sliding_attention": None
590
+ }
591
+ else:
592
+ mask_mapping = {
593
+ "full_attention": create_packed_seqs_mask(cu_seqlens, causal=not self.config.use_bidirectional_attention, device=hidden_states.device),
594
+ "sliding_attention": create_packed_seqs_mask(cu_seqlens, causal=not self.config.use_bidirectional_attention, device=hidden_states.device, window_size=window_size)
595
+ }
596
+
597
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
598
+ if output_hidden_states:
599
+ if attention_mask is not None:
600
+ all_hidden_states += (
601
+ cu_seqlens_to_batch_input(
602
+ hidden_states, cu_seqlens, attention_mask.shape[-1]
603
+ )[0],
604
+ )
605
+ else:
606
+ all_hidden_states += (hidden_states,)
607
+
608
+ layer_outputs = encoder_layer(
609
+ hidden_states,
610
+ position_embeddings_global=position_embeddings_global,
611
+ position_embeddings_local=position_embeddings_local,
612
+ attention_mask=mask_mapping[encoder_layer.attention_type],
613
+ cu_seqlens=cu_seqlens,
614
+ max_seqlen=max_seqlen,
615
+ window_size=window_size if encoder_layer.attention_type == "sliding_attention" else (-1, -1),
616
+ )
617
+
618
+ hidden_states = layer_outputs[0]
619
+ if output_attentions:
620
+ if attention_mask is not None:
621
+ all_self_attns += (
622
+ cu_attention_weight_to_batch(
623
+ layer_outputs[1], cu_seqlens, attention_mask.shape[-1]
624
+ ),
625
+ )
626
+
627
+ else:
628
+ all_self_attns += (layer_outputs[1],)
629
+
630
+ hidden_states = self.norm(hidden_states)
631
+ if attention_mask is not None:
632
+ hidden_states = cu_seqlens_to_batch_input(
633
+ hidden_states, cu_seqlens, attention_mask.shape[-1]
634
+ )
635
+ if output_hidden_states:
636
+ all_hidden_states += (hidden_states,)
637
+
638
+ # For MNTP XP
639
+ output = BaseModelOutput(
640
+ last_hidden_state=hidden_states[:, :-1, :],
641
+ hidden_states=tuple(h[:, :-1, :] for h in all_hidden_states) if all_hidden_states is not None else None,
642
+ attentions=tuple(a[:, :, :-1, :-1] for a in all_self_attns) if all_self_attns is not None else None,
643
+ )
644
+ return output if return_dict else output.to_tuple()
645
+
646
+
647
+ class BidirLMForMaskedLM(BidirLMPreTrainedModel):
648
+ _tied_weights_keys = ["lm_head.weight"]
649
+ config: BidirLMConfig
650
+
651
+ def __init__(self, config):
652
+ super().__init__(config)
653
+ self.model = BidirLMModel(config)
654
+ self.vocab_size = config.vocab_size
655
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
656
+
657
+ self.post_init()
658
+
659
+ def forward(
660
+ self,
661
+ input_ids: torch.LongTensor,
662
+ *,
663
+ attention_mask: Optional[torch.Tensor] = None,
664
+ cu_seqlens: Optional[torch.Tensor] = None,
665
+ max_seqlen: Optional[int] = None,
666
+ labels: Optional[torch.LongTensor] = None,
667
+ output_attentions: Optional[bool] = None,
668
+ output_hidden_states: Optional[bool] = None,
669
+ return_dict: Optional[bool] = None,
670
+ **kwargs,
671
+ ) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
672
+ return_dict = (
673
+ return_dict if return_dict is not None else self.config.use_return_dict
674
+ )
675
+ encoder_output = self.model(
676
+ input_ids=input_ids,
677
+ attention_mask=attention_mask,
678
+ cu_seqlens=cu_seqlens,
679
+ max_seqlen=max_seqlen,
680
+ output_attentions=output_attentions,
681
+ output_hidden_states=output_hidden_states,
682
+ return_dict=return_dict,
683
+ )
684
+
685
+ logits = self.lm_head(encoder_output[0])
686
+ if self.config.final_logit_softcapping is not None:
687
+ logits = logits / self.config.final_logit_softcapping
688
+ logits = torch.tanh(logits)
689
+ logits = logits * self.config.final_logit_softcapping
690
+
691
+ loss = None
692
+ if labels is not None:
693
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size)
694
+
695
+ output = MaskedLMOutput(
696
+ loss=loss,
697
+ logits=logits,
698
+ hidden_states=encoder_output.hidden_states,
699
+ attentions=encoder_output.attentions,
700
+ )
701
+ return output if return_dict else output.to_tuple()
702
+
703
+
704
+ class BidirLMForSequenceClassification(BidirLMPreTrainedModel):
705
+ config: BidirLMConfig
706
+
707
+ def __init__(self, config):
708
+ super().__init__(config)
709
+ self.num_labels = config.num_labels
710
+ self.classifier_pooling = config.classifier_pooling
711
+
712
+ self.model = BidirLMModel(config)
713
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
714
+ self.activation = nn.GELU()
715
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
716
+ self.post_init()
717
+
718
+ def forward(
719
+ self,
720
+ input_ids: Optional[torch.LongTensor] = None,
721
+ attention_mask: Optional[torch.Tensor] = None,
722
+ labels: Optional[torch.LongTensor] = None,
723
+ output_attentions: Optional[bool] = None,
724
+ output_hidden_states: Optional[bool] = None,
725
+ return_dict: Optional[bool] = None,
726
+ **kwargs,
727
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
728
+ return_dict = (
729
+ return_dict if return_dict is not None else self.config.use_return_dict
730
+ )
731
+
732
+ encoder_output = self.model(
733
+ input_ids,
734
+ attention_mask=attention_mask,
735
+ output_attentions=output_attentions,
736
+ output_hidden_states=output_hidden_states,
737
+ return_dict=return_dict,
738
+ )
739
+ last_hidden_state = encoder_output[0]
740
+
741
+ if self.classifier_pooling in ["bos", "mean"]:
742
+ if self.classifier_pooling == "bos":
743
+ pooled_output = last_hidden_state[:, 0]
744
+
745
+ elif self.classifier_pooling == "mean":
746
+ if attention_mask is None:
747
+ pooled_output = last_hidden_state.mean(dim=1)
748
+ else:
749
+ pooled_output = (
750
+ last_hidden_state * attention_mask.unsqueeze(-1)
751
+ ).sum(dim=1)
752
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
753
+
754
+ pooled_output = self.dense(pooled_output)
755
+ pooled_output = self.activation(pooled_output)
756
+ logits = self.classifier(pooled_output)
757
+ elif self.classifier_pooling == "late":
758
+ x = self.dense(last_hidden_state)
759
+ x = self.activation(x)
760
+ logits = self.classifier(x)
761
+ if attention_mask is None:
762
+ logits = logits.mean(dim=1)
763
+ else:
764
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
765
+ logits /= attention_mask.sum(dim=1, keepdim=True)
766
+
767
+ loss = None
768
+ if labels is not None:
769
+ labels = labels.to(logits.device)
770
+ if self.config.problem_type is None:
771
+ if self.num_labels == 1:
772
+ self.config.problem_type = "regression"
773
+ elif self.num_labels > 1 and (
774
+ labels.dtype == torch.long or labels.dtype == torch.int
775
+ ):
776
+ self.config.problem_type = "single_label_classification"
777
+ else:
778
+ self.config.problem_type = "multi_label_classification"
779
+
780
+ if self.config.problem_type == "regression":
781
+ loss_fct = MSELoss()
782
+ if self.num_labels == 1:
783
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
784
+ else:
785
+ loss = loss_fct(logits, labels)
786
+ elif self.config.problem_type == "single_label_classification":
787
+ loss_fct = CrossEntropyLoss()
788
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
789
+ elif self.config.problem_type == "multi_label_classification":
790
+ loss_fct = BCEWithLogitsLoss()
791
+ loss = loss_fct(logits, labels)
792
+
793
+ output = SequenceClassifierOutput(
794
+ loss=loss,
795
+ logits=logits,
796
+ hidden_states=encoder_output.hidden_states,
797
+ attentions=encoder_output.attentions,
798
+ )
799
+ return output if return_dict else output.to_tuple()
800
+
801
+
802
+ class BidirLMForTokenClassification(BidirLMPreTrainedModel):
803
+ config: BidirLMConfig
804
+
805
+ def __init__(self, config):
806
+ super().__init__(config)
807
+ self.num_labels = config.num_labels
808
+
809
+ self.model = BidirLMModel(config)
810
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
811
+ self.post_init()
812
+
813
+ def forward(
814
+ self,
815
+ input_ids: Optional[torch.LongTensor] = None,
816
+ attention_mask: Optional[torch.Tensor] = None,
817
+ position_ids: Optional[torch.LongTensor] = None,
818
+ inputs_embeds: Optional[torch.FloatTensor] = None,
819
+ labels: Optional[torch.LongTensor] = None,
820
+ use_cache: Optional[bool] = None,
821
+ output_attentions: Optional[bool] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ return_dict: Optional[bool] = None,
824
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
825
+ return_dict = (
826
+ return_dict if return_dict is not None else self.config.use_return_dict
827
+ )
828
+
829
+ outputs = self.model(
830
+ input_ids,
831
+ attention_mask=attention_mask,
832
+ position_ids=position_ids,
833
+ inputs_embeds=inputs_embeds,
834
+ use_cache=use_cache,
835
+ output_attentions=output_attentions,
836
+ output_hidden_states=output_hidden_states,
837
+ return_dict=return_dict,
838
+ )
839
+ sequence_output = outputs[0]
840
+ logits = self.classifier(sequence_output)
841
+
842
+ loss = None
843
+ if labels is not None:
844
+ loss_fct = CrossEntropyLoss()
845
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
846
+
847
+ if not return_dict:
848
+ output = (logits,) + outputs[2:]
849
+ return ((loss,) + output) if loss is not None else output
850
+
851
+ return TokenClassifierOutput(
852
+ loss=loss,
853
+ logits=logits,
854
+ hidden_states=outputs.hidden_states,
855
+ attentions=outputs.attentions,
856
+ )
857
+
858
+
859
+ # MultiModal
860
+ # class Gemma3Model(BidirLMPreTrainedModel):
861
+ # _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
862
+ # # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
863
+ # accepts_loss_kwargs = False
864
+
865
+ # def __init__(self, config: Gemma3Config):
866
+ # super().__init__(config)
867
+ # self.vision_tower = AutoModel.from_config(config=config.vision_config)
868
+ # self.multi_modal_projector = Gemma3MultiModalProjector(config)
869
+ # self.vocab_size = config.text_config.vocab_size
870
+
871
+ # language_model = AutoModel.from_config(config=config.text_config)
872
+ # self.language_model = language_model
873
+
874
+ # self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
875
+ # self.post_init()
876
+
877
+ # def get_input_embeddings(self):
878
+ # return self.language_model.get_input_embeddings()
879
+
880
+ # def set_input_embeddings(self, value):
881
+ # self.language_model.set_input_embeddings(value)
882
+
883
+ # def set_decoder(self, decoder):
884
+ # self.language_model = decoder
885
+
886
+ # def get_decoder(self):
887
+ # return self.language_model
888
+
889
+ # def get_image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
890
+ # """
891
+ # Projects the last hidden state from the vision model into language model space.
892
+
893
+ # Args:
894
+ # pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
895
+ # The tensors corresponding to the input images.
896
+ # Returns:
897
+ # image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
898
+ # """
899
+ # vision_outputs = self.vision_tower(pixel_values=pixel_values).last_hidden_state
900
+ # image_features = self.multi_modal_projector(vision_outputs)
901
+ # return image_features
902
+
903
+ # def get_placeholder_mask(
904
+ # self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
905
+ # ):
906
+ # """
907
+ # Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
908
+ # equal to the length of multimodal features. If the lengths are different, an error is raised.
909
+ # """
910
+ # if input_ids is None:
911
+ # special_image_mask = inputs_embeds == self.get_input_embeddings()(
912
+ # torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
913
+ # )
914
+ # special_image_mask = special_image_mask.all(-1)
915
+ # else:
916
+ # special_image_mask = input_ids == self.config.image_token_id
917
+
918
+ # n_image_tokens = special_image_mask.sum()
919
+ # special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
920
+ # n_image_features = image_features.shape[0] * image_features.shape[1]
921
+ # if inputs_embeds[special_image_mask].numel() != image_features.numel():
922
+ # raise ValueError(
923
+ # f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
924
+ # )
925
+ # return special_image_mask
926
+
927
+
928
+ # def forward(
929
+ # self,
930
+ # input_ids: Optional[torch.LongTensor] = None,
931
+ # pixel_values: Optional[torch.FloatTensor] = None,
932
+ # attention_mask: Optional[torch.Tensor] = None,
933
+ # position_ids: Optional[torch.LongTensor] = None,
934
+ # past_key_values: Optional[Cache] = None,
935
+ # token_type_ids: Optional[torch.LongTensor] = None,
936
+ # cache_position: Optional[torch.LongTensor] = None,
937
+ # inputs_embeds: Optional[torch.FloatTensor] = None,
938
+ # labels: Optional[torch.LongTensor] = None,
939
+ # use_cache: Optional[bool] = None,
940
+ # output_attentions: Optional[bool] = None,
941
+ # output_hidden_states: Optional[bool] = None,
942
+ # return_dict: Optional[bool] = None,
943
+ # **lm_kwargs,
944
+ # ) -> tuple:
945
+ # r"""
946
+ # labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
947
+ # Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
948
+ # config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
949
+ # (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
950
+
951
+ # Example:
952
+
953
+ # ```python
954
+ # >>> from PIL import Image
955
+ # >>> import requests
956
+ # >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
957
+
958
+ # >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma32-3b-mix-224")
959
+ # >>> processor = AutoProcessor.from_pretrained("google/gemma32-3b-mix-224")
960
+
961
+ # >>> prompt = "Where is the cat standing?"
962
+ # >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
963
+ # >>> image = Image.open(requests.get(url, stream=True).raw)
964
+
965
+ # >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
966
+
967
+ # >>> # Generate
968
+ # >>> generate_ids = model.generate(**inputs,)
969
+ # >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
970
+ # "Where is the cat standing?\nsnow"
971
+ # ```"""
972
+ # if (input_ids is None) ^ (inputs_embeds is not None):
973
+ # raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
974
+
975
+ # output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
976
+ # output_hidden_states = (
977
+ # output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
978
+ # )
979
+ # return_dict = return_dict if return_dict is not None else self.config.use_return_dict
980
+
981
+ # # Replace image id with PAD if the image token if OOV, to avoid index-errors
982
+ # if input_ids is not None and self.config.image_token_id >= self.vocab_size:
983
+ # special_image_mask = input_ids == self.config.image_token_id
984
+ # llm_input_ids = input_ids.clone()
985
+ # llm_input_ids[special_image_mask] = 0
986
+ # else:
987
+ # llm_input_ids = input_ids
988
+
989
+ # if inputs_embeds is None:
990
+ # inputs_embeds = self.get_input_embeddings()(llm_input_ids)
991
+
992
+ # if cache_position is None:
993
+ # past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
994
+ # cache_position = torch.arange(
995
+ # past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
996
+ # )
997
+
998
+ # # Merge text and images
999
+ # if pixel_values is not None:
1000
+ # image_features = self.get_image_features(pixel_values)
1001
+ # image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
1002
+ # special_image_mask = self.get_placeholder_mask(
1003
+ # input_ids, inputs_embeds=inputs_embeds, image_features=image_features
1004
+ # )
1005
+ # inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
1006
+
1007
+ # # It may already have been prepared by e.g. `generate`
1008
+ # if not isinstance(causal_mask_mapping := attention_mask, dict):
1009
+ # # Prepare mask arguments
1010
+ # mask_kwargs = {
1011
+ # "config": self.config.get_text_config(),
1012
+ # "input_embeds": inputs_embeds,
1013
+ # "attention_mask": attention_mask,
1014
+ # "cache_position": cache_position,
1015
+ # "past_key_values": past_key_values,
1016
+ # "position_ids": position_ids,
1017
+ # }
1018
+ # # NOTE: this `is_prefill` logic is not flawless, it fails when we're using a cache eagerly initialized
1019
+ # # (e.g. compiled prefill) AND `pixel_values` are not provided. Determining prefill in that case requires
1020
+ # # checking data values, which is not compile-compatible.
1021
+ # is_prefill = (
1022
+ # not use_cache
1023
+ # or past_key_values is None
1024
+ # or not past_key_values.is_initialized
1025
+ # or pixel_values is not None
1026
+ # )
1027
+ # if token_type_ids is not None and is_prefill:
1028
+ # # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
1029
+
1030
+ # # First find where a new image block starts: 1 if image and previous not image
1031
+ # # The images cannot attend to future images, but can attend to all prev images and to itself
1032
+ # # bidirectionally
1033
+ # is_image = (token_type_ids == 1).to(cache_position.device)
1034
+ # new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
1035
+ # image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
1036
+ # image_group_ids = torch.where(
1037
+ # is_image, image_group_ids, torch.full_like(token_type_ids, -1, device=is_image.device)
1038
+ # )
1039
+ # mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
1040
+ # token_type_ids.to(cache_position.device), image_group_ids, self.config.mm_tokens_per_image
1041
+ # )
1042
+
1043
+ # # Create the masks
1044
+ # causal_mask_mapping = {
1045
+ # "full_attention": create_causal_mask(**mask_kwargs),
1046
+ # "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
1047
+ # }
1048
+
1049
+ # outputs = self.language_model(
1050
+ # attention_mask=causal_mask_mapping,
1051
+ # position_ids=position_ids,
1052
+ # past_key_values=past_key_values,
1053
+ # inputs_embeds=inputs_embeds,
1054
+ # use_cache=use_cache,
1055
+ # output_attentions=output_attentions,
1056
+ # output_hidden_states=output_hidden_states,
1057
+ # return_dict=True,
1058
+ # cache_position=cache_position,
1059
+ # **lm_kwargs,
1060
+ # )
1061
+
1062
+ # return (
1063
+ # outputs,
1064
+ # image_features if pixel_values is not None else None,
1065
+ # )
1066
+
1067
+ # class Gemma3MultiModalProjector(nn.Module):
1068
+ # def __init__(self, config: Gemma3Config):
1069
+ # super().__init__()
1070
+
1071
+ # self.mm_input_projection_weight = nn.Parameter(
1072
+ # torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
1073
+ # )
1074
+
1075
+ # self.mm_soft_emb_norm = Gemma3RMSNorm(
1076
+ # config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
1077
+ # )
1078
+
1079
+ # self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
1080
+ # self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
1081
+ # self.kernel_size = self.patches_per_image // self.tokens_per_side
1082
+ # self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
1083
+
1084
+ # def forward(self, vision_outputs: torch.Tensor):
1085
+ # batch_size, _, seq_length = vision_outputs.shape
1086
+
1087
+ # reshaped_vision_outputs = vision_outputs.transpose(1, 2)
1088
+ # reshaped_vision_outputs = reshaped_vision_outputs.reshape(
1089
+ # batch_size, seq_length, self.patches_per_image, self.patches_per_image
1090
+ # )
1091
+ # reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
1092
+
1093
+ # pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
1094
+ # pooled_vision_outputs = pooled_vision_outputs.flatten(2)
1095
+ # pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
1096
+
1097
+ # normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
1098
+
1099
+ # projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
1100
+ # return projected_vision_outputs.type_as(vision_outputs)
1101
+
1102
+ # def token_type_ids_mask_function(
1103
+ # token_type_ids: Optional[torch.Tensor],
1104
+ # image_group_ids: Optional[torch.Tensor],
1105
+ # tokens_per_image: int,
1106
+ # ) -> Optional[Callable]:
1107
+ # """
1108
+ # This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths,
1109
+ # not start and end indices.
1110
+ # """
1111
+ # # Do not return an additional mask in this case
1112
+ # if token_type_ids is None:
1113
+ # return None
1114
+
1115
+ # def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
1116
+ # # If it's 1 for both query and key/value, we are in an image block
1117
+ # # NOTE: static cache shape goes beyond input seq length, while token_type_ids.shape[1] == input seq length
1118
+ # # Since vmap doesn't support `if statement` we workaround it with `torch.where`
1119
+ # safe_idx = torch.where(kv_idx < token_type_ids.shape[1], kv_idx, 0)
1120
+ # token_type_ids_at_kv_idx = token_type_ids[batch_idx, safe_idx]
1121
+ # token_type_ids_at_kv_idx = torch.where(kv_idx < token_type_ids.shape[1], token_type_ids_at_kv_idx, 0)
1122
+
1123
+ # image_group_ids_at_kv_idx = image_group_ids[batch_idx, safe_idx]
1124
+ # image_group_ids_at_kv_idx = torch.where(kv_idx < image_group_ids.shape[1], image_group_ids_at_kv_idx, -1)
1125
+
1126
+ # is_image_block = (token_type_ids[batch_idx, q_idx] == 1) & (token_type_ids_at_kv_idx == 1)
1127
+ # same_image_block = image_group_ids[batch_idx, q_idx] == image_group_ids_at_kv_idx
1128
+
1129
+ # # This is bidirectional attention whenever we are dealing with image tokens
1130
+ # return is_image_block & same_image_block
1131
+
1132
+ # return inner_mask
1133
+
1134
+
1135
+ __all__ = [
1136
+ "BidirLMPreTrainedModel",
1137
+ "BidirLMModel",
1138
+ "BidirLMForMaskedLM",
1139
+ "BidirLMForSequenceClassification",
1140
+ "BidirLMForTokenClassification",
1141
+ # "Gemma3Model",
1142
+ ]
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,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "boi_token": "<start_of_image>",
3
+ "bos_token": {
4
+ "content": "<bos>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ "eoi_token": "<end_of_image>",
11
+ "eos_token": {
12
+ "content": "<eos>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "image_token": "<image_soft_token>",
19
+ "mask_token": "<|mask|>",
20
+ "pad_token": {
21
+ "content": "<pad>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "unk_token": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c455eff9eed1fa5ff7516f571d38590863030c6dbd835c65f35fdc77d21ca3e4
3
+ size 33384562
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c
3
+ size 4689074
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff