Add new SentenceTransformer model
Browse files- .gitattributes +1 -0
- 1_Pooling/config.json +10 -0
- README.md +528 -0
- config.json +67 -0
- config_sentence_transformers.json +16 -0
- custom_st.py +229 -0
- model.safetensors +3 -0
- modules.json +20 -0
- sentence_bert_config.json +4 -0
- special_tokens_map.json +51 -0
- tokenizer.json +3 -0
- tokenizer_config.json +54 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ 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 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
1_Pooling/config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"word_embedding_dimension": 1024,
|
3 |
+
"pooling_mode_cls_token": false,
|
4 |
+
"pooling_mode_mean_tokens": true,
|
5 |
+
"pooling_mode_max_tokens": false,
|
6 |
+
"pooling_mode_mean_sqrt_len_tokens": false,
|
7 |
+
"pooling_mode_weightedmean_tokens": false,
|
8 |
+
"pooling_mode_lasttoken": false,
|
9 |
+
"include_prompt": true
|
10 |
+
}
|
README.md
ADDED
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
base_model: jinaai/jina-embeddings-v3
|
3 |
+
library_name: sentence-transformers
|
4 |
+
metrics:
|
5 |
+
- pearson_cosine
|
6 |
+
- spearman_cosine
|
7 |
+
pipeline_tag: sentence-similarity
|
8 |
+
tags:
|
9 |
+
- sentence-transformers
|
10 |
+
- sentence-similarity
|
11 |
+
- feature-extraction
|
12 |
+
- generated_from_trainer
|
13 |
+
- dataset_size:63802
|
14 |
+
- loss:CoSENTLoss
|
15 |
+
widget:
|
16 |
+
- source_sentence: машинка детская самоходная бибикар желтый
|
17 |
+
sentences:
|
18 |
+
- 'машинка детская красная бибикар '
|
19 |
+
- моторное масло alpine dx1 5w 30 5л 0101662
|
20 |
+
- 'спинбайк schwinn ic7 '
|
21 |
+
- source_sentence: 'велосипед stels saber 20 фиолетовый '
|
22 |
+
sentences:
|
23 |
+
- 'детские спортивные комплексы '
|
24 |
+
- 'велосипед bmx stels saber 20 v010 2020 '
|
25 |
+
- 50218 кабель ugreen hd132 hdmi zinc alloy optical fiber cable черный 40m
|
26 |
+
- source_sentence: гидравличесские прессы
|
27 |
+
sentences:
|
28 |
+
- пресс гидравлический ручной механизмом
|
29 |
+
- ракетка для настольного тенниса fora 7
|
30 |
+
- 'объектив panasonic 20mm f1 7 asph ii h h020ae k '
|
31 |
+
- source_sentence: 'бокс пластиковый монтажной платой щмп п 300х200х130 мм ip65 proxima
|
32 |
+
ящики щитки шкафы '
|
33 |
+
sentences:
|
34 |
+
- батарейный отсек для 4xаа открытый проволочные выводы разъем dcx2 1 battery holder
|
35 |
+
4xaa 6v dc
|
36 |
+
- 'bugera bc15 '
|
37 |
+
- 'бокс пластиковый монтажной платой щмп п 500х350х190 мм ip65 proxima ящики щитки
|
38 |
+
шкафы '
|
39 |
+
- source_sentence: 'honor watch gs pro black '
|
40 |
+
sentences:
|
41 |
+
- 'honor watch gs pro white '
|
42 |
+
- трансформер pituso carlo hb gy 06 lemon
|
43 |
+
- 'электровелосипед колхозник volten greenline 500w '
|
44 |
+
model-index:
|
45 |
+
- name: SentenceTransformer based on jinaai/jina-embeddings-v3
|
46 |
+
results:
|
47 |
+
- task:
|
48 |
+
type: semantic-similarity
|
49 |
+
name: Semantic Similarity
|
50 |
+
dataset:
|
51 |
+
name: example dev
|
52 |
+
type: example-dev
|
53 |
+
metrics:
|
54 |
+
- type: pearson_cosine
|
55 |
+
value: 0.47736782328677585
|
56 |
+
name: Pearson Cosine
|
57 |
+
- type: spearman_cosine
|
58 |
+
value: 0.49693031448879005
|
59 |
+
name: Spearman Cosine
|
60 |
+
---
|
61 |
+
|
62 |
+
# SentenceTransformer based on jinaai/jina-embeddings-v3
|
63 |
+
|
64 |
+
This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [jinaai/jina-embeddings-v3](https://huggingface.co/jinaai/jina-embeddings-v3). It maps sentences & paragraphs to a 1024-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
|
65 |
+
|
66 |
+
## Model Details
|
67 |
+
|
68 |
+
### Model Description
|
69 |
+
- **Model Type:** Sentence Transformer
|
70 |
+
- **Base model:** [jinaai/jina-embeddings-v3](https://huggingface.co/jinaai/jina-embeddings-v3) <!-- at revision 30996fea06f69ecd8382ee4f11e29acaf6b5405e -->
|
71 |
+
- **Maximum Sequence Length:** 8194 tokens
|
72 |
+
- **Output Dimensionality:** 1024 dimensions
|
73 |
+
- **Similarity Function:** Cosine Similarity
|
74 |
+
<!-- - **Training Dataset:** Unknown -->
|
75 |
+
<!-- - **Language:** Unknown -->
|
76 |
+
<!-- - **License:** Unknown -->
|
77 |
+
|
78 |
+
### Model Sources
|
79 |
+
|
80 |
+
- **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
|
81 |
+
- **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
|
82 |
+
- **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
|
83 |
+
|
84 |
+
### Full Model Architecture
|
85 |
+
|
86 |
+
```
|
87 |
+
SentenceTransformer(
|
88 |
+
(transformer): Transformer(
|
89 |
+
(auto_model): XLMRobertaLoRA(
|
90 |
+
(roberta): XLMRobertaModel(
|
91 |
+
(embeddings): XLMRobertaEmbeddings(
|
92 |
+
(word_embeddings): ParametrizedEmbedding(
|
93 |
+
250002, 1024, padding_idx=1
|
94 |
+
(parametrizations): ModuleDict(
|
95 |
+
(weight): ParametrizationList(
|
96 |
+
(0): LoRAParametrization()
|
97 |
+
)
|
98 |
+
)
|
99 |
+
)
|
100 |
+
(token_type_embeddings): ParametrizedEmbedding(
|
101 |
+
1, 1024
|
102 |
+
(parametrizations): ModuleDict(
|
103 |
+
(weight): ParametrizationList(
|
104 |
+
(0): LoRAParametrization()
|
105 |
+
)
|
106 |
+
)
|
107 |
+
)
|
108 |
+
)
|
109 |
+
(emb_drop): Dropout(p=0.1, inplace=False)
|
110 |
+
(emb_ln): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
|
111 |
+
(encoder): XLMRobertaEncoder(
|
112 |
+
(layers): ModuleList(
|
113 |
+
(0-23): 24 x Block(
|
114 |
+
(mixer): MHA(
|
115 |
+
(rotary_emb): RotaryEmbedding()
|
116 |
+
(Wqkv): ParametrizedLinearResidual(
|
117 |
+
in_features=1024, out_features=3072, bias=True
|
118 |
+
(parametrizations): ModuleDict(
|
119 |
+
(weight): ParametrizationList(
|
120 |
+
(0): LoRAParametrization()
|
121 |
+
)
|
122 |
+
)
|
123 |
+
)
|
124 |
+
(inner_attn): SelfAttention(
|
125 |
+
(drop): Dropout(p=0.1, inplace=False)
|
126 |
+
)
|
127 |
+
(inner_cross_attn): CrossAttention(
|
128 |
+
(drop): Dropout(p=0.1, inplace=False)
|
129 |
+
)
|
130 |
+
(out_proj): ParametrizedLinear(
|
131 |
+
in_features=1024, out_features=1024, bias=True
|
132 |
+
(parametrizations): ModuleDict(
|
133 |
+
(weight): ParametrizationList(
|
134 |
+
(0): LoRAParametrization()
|
135 |
+
)
|
136 |
+
)
|
137 |
+
)
|
138 |
+
)
|
139 |
+
(dropout1): Dropout(p=0.1, inplace=False)
|
140 |
+
(drop_path1): StochasticDepth(p=0.0, mode=row)
|
141 |
+
(norm1): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
|
142 |
+
(mlp): Mlp(
|
143 |
+
(fc1): ParametrizedLinear(
|
144 |
+
in_features=1024, out_features=4096, bias=True
|
145 |
+
(parametrizations): ModuleDict(
|
146 |
+
(weight): ParametrizationList(
|
147 |
+
(0): LoRAParametrization()
|
148 |
+
)
|
149 |
+
)
|
150 |
+
)
|
151 |
+
(fc2): ParametrizedLinear(
|
152 |
+
in_features=4096, out_features=1024, bias=True
|
153 |
+
(parametrizations): ModuleDict(
|
154 |
+
(weight): ParametrizationList(
|
155 |
+
(0): LoRAParametrization()
|
156 |
+
)
|
157 |
+
)
|
158 |
+
)
|
159 |
+
)
|
160 |
+
(dropout2): Dropout(p=0.1, inplace=False)
|
161 |
+
(drop_path2): StochasticDepth(p=0.0, mode=row)
|
162 |
+
(norm2): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
|
163 |
+
)
|
164 |
+
)
|
165 |
+
)
|
166 |
+
(pooler): XLMRobertaPooler(
|
167 |
+
(dense): ParametrizedLinear(
|
168 |
+
in_features=1024, out_features=1024, bias=True
|
169 |
+
(parametrizations): ModuleDict(
|
170 |
+
(weight): ParametrizationList(
|
171 |
+
(0): LoRAParametrization()
|
172 |
+
)
|
173 |
+
)
|
174 |
+
)
|
175 |
+
(activation): Tanh()
|
176 |
+
)
|
177 |
+
)
|
178 |
+
)
|
179 |
+
)
|
180 |
+
(pooler): Pooling({'word_embedding_dimension': 1024, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
|
181 |
+
(normalizer): Normalize()
|
182 |
+
)
|
183 |
+
```
|
184 |
+
|
185 |
+
## Usage
|
186 |
+
|
187 |
+
### Direct Usage (Sentence Transformers)
|
188 |
+
|
189 |
+
First install the Sentence Transformers library:
|
190 |
+
|
191 |
+
```bash
|
192 |
+
pip install -U sentence-transformers
|
193 |
+
```
|
194 |
+
|
195 |
+
Then you can load this model and run inference.
|
196 |
+
```python
|
197 |
+
from sentence_transformers import SentenceTransformer
|
198 |
+
|
199 |
+
# Download from the 🤗 Hub
|
200 |
+
model = SentenceTransformer("seregadgl/t2")
|
201 |
+
# Run inference
|
202 |
+
sentences = [
|
203 |
+
'honor watch gs pro black ',
|
204 |
+
'honor watch gs pro white ',
|
205 |
+
'трансформер pituso carlo hb gy 06 lemon',
|
206 |
+
]
|
207 |
+
embeddings = model.encode(sentences)
|
208 |
+
print(embeddings.shape)
|
209 |
+
# [3, 1024]
|
210 |
+
|
211 |
+
# Get the similarity scores for the embeddings
|
212 |
+
similarities = model.similarity(embeddings, embeddings)
|
213 |
+
print(similarities.shape)
|
214 |
+
# [3, 3]
|
215 |
+
```
|
216 |
+
|
217 |
+
<!--
|
218 |
+
### Direct Usage (Transformers)
|
219 |
+
|
220 |
+
<details><summary>Click to see the direct usage in Transformers</summary>
|
221 |
+
|
222 |
+
</details>
|
223 |
+
-->
|
224 |
+
|
225 |
+
<!--
|
226 |
+
### Downstream Usage (Sentence Transformers)
|
227 |
+
|
228 |
+
You can finetune this model on your own dataset.
|
229 |
+
|
230 |
+
<details><summary>Click to expand</summary>
|
231 |
+
|
232 |
+
</details>
|
233 |
+
-->
|
234 |
+
|
235 |
+
<!--
|
236 |
+
### Out-of-Scope Use
|
237 |
+
|
238 |
+
*List how the model may foreseeably be misused and address what users ought not to do with the model.*
|
239 |
+
-->
|
240 |
+
|
241 |
+
## Evaluation
|
242 |
+
|
243 |
+
### Metrics
|
244 |
+
|
245 |
+
#### Semantic Similarity
|
246 |
+
|
247 |
+
* Dataset: `example-dev`
|
248 |
+
* Evaluated with [<code>EmbeddingSimilarityEvaluator</code>](https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html#sentence_transformers.evaluation.EmbeddingSimilarityEvaluator)
|
249 |
+
|
250 |
+
| Metric | Value |
|
251 |
+
|:--------------------|:-----------|
|
252 |
+
| pearson_cosine | 0.4774 |
|
253 |
+
| **spearman_cosine** | **0.4969** |
|
254 |
+
|
255 |
+
<!--
|
256 |
+
## Bias, Risks and Limitations
|
257 |
+
|
258 |
+
*What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
|
259 |
+
-->
|
260 |
+
|
261 |
+
<!--
|
262 |
+
### Recommendations
|
263 |
+
|
264 |
+
*What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
|
265 |
+
-->
|
266 |
+
|
267 |
+
## Training Details
|
268 |
+
|
269 |
+
### Training Dataset
|
270 |
+
|
271 |
+
#### Unnamed Dataset
|
272 |
+
|
273 |
+
|
274 |
+
* Size: 63,802 training samples
|
275 |
+
* Columns: <code>doc</code>, <code>candidate</code>, and <code>label</code>
|
276 |
+
* Approximate statistics based on the first 1000 samples:
|
277 |
+
| | doc | candidate | label |
|
278 |
+
|:--------|:----------------------------------------------------------------------------------|:----------------------------------------------------------------------------------|:------------------------------------------------|
|
279 |
+
| type | string | string | int |
|
280 |
+
| details | <ul><li>min: 3 tokens</li><li>mean: 14.82 tokens</li><li>max: 55 tokens</li></ul> | <ul><li>min: 4 tokens</li><li>mean: 14.58 tokens</li><li>max: 37 tokens</li></ul> | <ul><li>0: ~85.20%</li><li>1: ~14.80%</li></ul> |
|
281 |
+
* Samples:
|
282 |
+
| doc | candidate | label |
|
283 |
+
|:-------------------------------------------------------|:-----------------------------------------------------------------------|:---------------|
|
284 |
+
| <code>массажер xiaomi massage gun eu bhr5608eu </code> | <code>перкуссионный массажер xiaomi massage gun mini bhr6083gl </code> | <code>0</code> |
|
285 |
+
| <code>безударная дрель ingco ed50028 </code> | <code>ударная дрель ingco id211002 </code> | <code>0</code> |
|
286 |
+
| <code>жидкость old smuggler 30мл 20мг </code> | <code>жидкость old smuggler salt 30ml marlboro 20mg</code> | <code>0</code> |
|
287 |
+
* Loss: [<code>CoSENTLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cosentloss) with these parameters:
|
288 |
+
```json
|
289 |
+
{
|
290 |
+
"scale": 20.0,
|
291 |
+
"similarity_fct": "pairwise_cos_sim"
|
292 |
+
}
|
293 |
+
```
|
294 |
+
|
295 |
+
### Evaluation Dataset
|
296 |
+
|
297 |
+
#### Unnamed Dataset
|
298 |
+
|
299 |
+
|
300 |
+
* Size: 7,090 evaluation samples
|
301 |
+
* Columns: <code>doc</code>, <code>candidate</code>, and <code>label</code>
|
302 |
+
* Approximate statistics based on the first 1000 samples:
|
303 |
+
| | doc | candidate | label |
|
304 |
+
|:--------|:----------------------------------------------------------------------------------|:----------------------------------------------------------------------------------|:------------------------------------------------|
|
305 |
+
| type | string | string | int |
|
306 |
+
| details | <ul><li>min: 4 tokens</li><li>mean: 14.91 tokens</li><li>max: 72 tokens</li></ul> | <ul><li>min: 4 tokens</li><li>mean: 14.56 tokens</li><li>max: 51 tokens</li></ul> | <ul><li>0: ~84.20%</li><li>1: ~15.80%</li></ul> |
|
307 |
+
* Samples:
|
308 |
+
| doc | candidate | label |
|
309 |
+
|:--------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------|:---------------|
|
310 |
+
| <code>круглое пляжное парео селфи коврик пляжная подстилка пляжное покрывало пляжный коврик пироженко </code> | <code>круглое пляжное парео селфи коврик пляжная подстилка пляжное покрывало пляжный коврик клубника </code> | <code>0</code> |
|
311 |
+
| <code>аккумулятор батарея для ноутбука asus g751 </code> | <code>аккумулятор батарея для ноутбука asus g75 series</code> | <code>0</code> |
|
312 |
+
| <code>миксер bosch mfq3520 mfq 3520 </code> | <code>миксер bosch mfq 4020 </code> | <code>0</code> |
|
313 |
+
* Loss: [<code>CoSENTLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cosentloss) with these parameters:
|
314 |
+
```json
|
315 |
+
{
|
316 |
+
"scale": 20.0,
|
317 |
+
"similarity_fct": "pairwise_cos_sim"
|
318 |
+
}
|
319 |
+
```
|
320 |
+
|
321 |
+
### Training Hyperparameters
|
322 |
+
#### Non-Default Hyperparameters
|
323 |
+
|
324 |
+
- `eval_strategy`: steps
|
325 |
+
- `per_device_train_batch_size`: 16
|
326 |
+
- `per_device_eval_batch_size`: 16
|
327 |
+
- `num_train_epochs`: 2
|
328 |
+
- `lr_scheduler_type`: cosine
|
329 |
+
- `warmup_ratio`: 0.1
|
330 |
+
- `load_best_model_at_end`: True
|
331 |
+
- `batch_sampler`: no_duplicates
|
332 |
+
|
333 |
+
#### All Hyperparameters
|
334 |
+
<details><summary>Click to expand</summary>
|
335 |
+
|
336 |
+
- `overwrite_output_dir`: False
|
337 |
+
- `do_predict`: False
|
338 |
+
- `eval_strategy`: steps
|
339 |
+
- `prediction_loss_only`: True
|
340 |
+
- `per_device_train_batch_size`: 16
|
341 |
+
- `per_device_eval_batch_size`: 16
|
342 |
+
- `per_gpu_train_batch_size`: None
|
343 |
+
- `per_gpu_eval_batch_size`: None
|
344 |
+
- `gradient_accumulation_steps`: 1
|
345 |
+
- `eval_accumulation_steps`: None
|
346 |
+
- `torch_empty_cache_steps`: None
|
347 |
+
- `learning_rate`: 5e-05
|
348 |
+
- `weight_decay`: 0.0
|
349 |
+
- `adam_beta1`: 0.9
|
350 |
+
- `adam_beta2`: 0.999
|
351 |
+
- `adam_epsilon`: 1e-08
|
352 |
+
- `max_grad_norm`: 1.0
|
353 |
+
- `num_train_epochs`: 2
|
354 |
+
- `max_steps`: -1
|
355 |
+
- `lr_scheduler_type`: cosine
|
356 |
+
- `lr_scheduler_kwargs`: {}
|
357 |
+
- `warmup_ratio`: 0.1
|
358 |
+
- `warmup_steps`: 0
|
359 |
+
- `log_level`: passive
|
360 |
+
- `log_level_replica`: warning
|
361 |
+
- `log_on_each_node`: True
|
362 |
+
- `logging_nan_inf_filter`: True
|
363 |
+
- `save_safetensors`: True
|
364 |
+
- `save_on_each_node`: False
|
365 |
+
- `save_only_model`: False
|
366 |
+
- `restore_callback_states_from_checkpoint`: False
|
367 |
+
- `no_cuda`: False
|
368 |
+
- `use_cpu`: False
|
369 |
+
- `use_mps_device`: False
|
370 |
+
- `seed`: 42
|
371 |
+
- `data_seed`: None
|
372 |
+
- `jit_mode_eval`: False
|
373 |
+
- `use_ipex`: False
|
374 |
+
- `bf16`: False
|
375 |
+
- `fp16`: False
|
376 |
+
- `fp16_opt_level`: O1
|
377 |
+
- `half_precision_backend`: auto
|
378 |
+
- `bf16_full_eval`: False
|
379 |
+
- `fp16_full_eval`: False
|
380 |
+
- `tf32`: None
|
381 |
+
- `local_rank`: 0
|
382 |
+
- `ddp_backend`: None
|
383 |
+
- `tpu_num_cores`: None
|
384 |
+
- `tpu_metrics_debug`: False
|
385 |
+
- `debug`: []
|
386 |
+
- `dataloader_drop_last`: False
|
387 |
+
- `dataloader_num_workers`: 0
|
388 |
+
- `dataloader_prefetch_factor`: None
|
389 |
+
- `past_index`: -1
|
390 |
+
- `disable_tqdm`: False
|
391 |
+
- `remove_unused_columns`: True
|
392 |
+
- `label_names`: None
|
393 |
+
- `load_best_model_at_end`: True
|
394 |
+
- `ignore_data_skip`: False
|
395 |
+
- `fsdp`: []
|
396 |
+
- `fsdp_min_num_params`: 0
|
397 |
+
- `fsdp_config`: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
|
398 |
+
- `fsdp_transformer_layer_cls_to_wrap`: None
|
399 |
+
- `accelerator_config`: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
|
400 |
+
- `deepspeed`: None
|
401 |
+
- `label_smoothing_factor`: 0.0
|
402 |
+
- `optim`: adamw_torch
|
403 |
+
- `optim_args`: None
|
404 |
+
- `adafactor`: False
|
405 |
+
- `group_by_length`: False
|
406 |
+
- `length_column_name`: length
|
407 |
+
- `ddp_find_unused_parameters`: None
|
408 |
+
- `ddp_bucket_cap_mb`: None
|
409 |
+
- `ddp_broadcast_buffers`: False
|
410 |
+
- `dataloader_pin_memory`: True
|
411 |
+
- `dataloader_persistent_workers`: False
|
412 |
+
- `skip_memory_metrics`: True
|
413 |
+
- `use_legacy_prediction_loop`: False
|
414 |
+
- `push_to_hub`: False
|
415 |
+
- `resume_from_checkpoint`: None
|
416 |
+
- `hub_model_id`: None
|
417 |
+
- `hub_strategy`: every_save
|
418 |
+
- `hub_private_repo`: False
|
419 |
+
- `hub_always_push`: False
|
420 |
+
- `gradient_checkpointing`: False
|
421 |
+
- `gradient_checkpointing_kwargs`: None
|
422 |
+
- `include_inputs_for_metrics`: False
|
423 |
+
- `include_for_metrics`: []
|
424 |
+
- `eval_do_concat_batches`: True
|
425 |
+
- `fp16_backend`: auto
|
426 |
+
- `push_to_hub_model_id`: None
|
427 |
+
- `push_to_hub_organization`: None
|
428 |
+
- `mp_parameters`:
|
429 |
+
- `auto_find_batch_size`: False
|
430 |
+
- `full_determinism`: False
|
431 |
+
- `torchdynamo`: None
|
432 |
+
- `ray_scope`: last
|
433 |
+
- `ddp_timeout`: 1800
|
434 |
+
- `torch_compile`: False
|
435 |
+
- `torch_compile_backend`: None
|
436 |
+
- `torch_compile_mode`: None
|
437 |
+
- `dispatch_batches`: None
|
438 |
+
- `split_batches`: None
|
439 |
+
- `include_tokens_per_second`: False
|
440 |
+
- `include_num_input_tokens_seen`: False
|
441 |
+
- `neftune_noise_alpha`: None
|
442 |
+
- `optim_target_modules`: None
|
443 |
+
- `batch_eval_metrics`: False
|
444 |
+
- `eval_on_start`: False
|
445 |
+
- `use_liger_kernel`: False
|
446 |
+
- `eval_use_gather_object`: False
|
447 |
+
- `average_tokens_across_devices`: False
|
448 |
+
- `prompts`: None
|
449 |
+
- `batch_sampler`: no_duplicates
|
450 |
+
- `multi_dataset_batch_sampler`: proportional
|
451 |
+
|
452 |
+
</details>
|
453 |
+
|
454 |
+
### Training Logs
|
455 |
+
| Epoch | Step | Training Loss | Validation Loss | example-dev_spearman_cosine |
|
456 |
+
|:------:|:----:|:-------------:|:---------------:|:---------------------------:|
|
457 |
+
| 0 | 0 | - | - | 0.1562 |
|
458 |
+
| 0.1254 | 500 | 4.2363 | 3.5101 | 0.3313 |
|
459 |
+
| 0.2508 | 1000 | 3.0049 | 2.8592 | 0.4536 |
|
460 |
+
| 0.3761 | 1500 | 2.6306 | 2.8977 | 0.4704 |
|
461 |
+
| 0.5015 | 2000 | 2.6472 | 2.6703 | 0.4827 |
|
462 |
+
| 0.6269 | 2500 | 2.6626 | 2.6757 | 0.4837 |
|
463 |
+
| 0.7523 | 3000 | 2.6137 | 2.6397 | 0.4883 |
|
464 |
+
| 0.8776 | 3500 | 2.676 | 2.5394 | 0.4936 |
|
465 |
+
| 1.0030 | 4000 | 2.4997 | 2.5984 | 0.4931 |
|
466 |
+
| 1.1284 | 4500 | 2.4901 | 2.6219 | 0.4946 |
|
467 |
+
| 1.2538 | 5000 | 2.4293 | 2.6319 | 0.4943 |
|
468 |
+
| 1.3791 | 5500 | 2.3914 | 2.7122 | 0.4936 |
|
469 |
+
| 1.5045 | 6000 | 2.465 | 2.6573 | 0.4970 |
|
470 |
+
| 1.6299 | 6500 | 2.5711 | 2.6388 | 0.4965 |
|
471 |
+
| 1.7553 | 7000 | 2.5012 | 2.6323 | 0.4967 |
|
472 |
+
| 1.8806 | 7500 | 2.5775 | 2.6231 | 0.4969 |
|
473 |
+
|
474 |
+
|
475 |
+
### Framework Versions
|
476 |
+
- Python: 3.10.14
|
477 |
+
- Sentence Transformers: 3.3.1
|
478 |
+
- Transformers: 4.46.3
|
479 |
+
- PyTorch: 2.4.0
|
480 |
+
- Accelerate: 0.34.2
|
481 |
+
- Datasets: 3.0.1
|
482 |
+
- Tokenizers: 0.20.0
|
483 |
+
|
484 |
+
## Citation
|
485 |
+
|
486 |
+
### BibTeX
|
487 |
+
|
488 |
+
#### Sentence Transformers
|
489 |
+
```bibtex
|
490 |
+
@inproceedings{reimers-2019-sentence-bert,
|
491 |
+
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
|
492 |
+
author = "Reimers, Nils and Gurevych, Iryna",
|
493 |
+
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
|
494 |
+
month = "11",
|
495 |
+
year = "2019",
|
496 |
+
publisher = "Association for Computational Linguistics",
|
497 |
+
url = "https://arxiv.org/abs/1908.10084",
|
498 |
+
}
|
499 |
+
```
|
500 |
+
|
501 |
+
#### CoSENTLoss
|
502 |
+
```bibtex
|
503 |
+
@online{kexuefm-8847,
|
504 |
+
title={CoSENT: A more efficient sentence vector scheme than Sentence-BERT},
|
505 |
+
author={Su Jianlin},
|
506 |
+
year={2022},
|
507 |
+
month={Jan},
|
508 |
+
url={https://kexue.fm/archives/8847},
|
509 |
+
}
|
510 |
+
```
|
511 |
+
|
512 |
+
<!--
|
513 |
+
## Glossary
|
514 |
+
|
515 |
+
*Clearly define terms in order to be accessible across audiences.*
|
516 |
+
-->
|
517 |
+
|
518 |
+
<!--
|
519 |
+
## Model Card Authors
|
520 |
+
|
521 |
+
*Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
|
522 |
+
-->
|
523 |
+
|
524 |
+
<!--
|
525 |
+
## Model Card Contact
|
526 |
+
|
527 |
+
*Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
|
528 |
+
-->
|
config.json
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "jinaai/jina-embeddings-v3",
|
3 |
+
"architectures": [
|
4 |
+
"XLMRobertaLoRA"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "jinaai/xlm-roberta-flash-implementation--configuration_xlm_roberta.XLMRobertaFlashConfig",
|
9 |
+
"AutoModel": "jinaai/xlm-roberta-flash-implementation--modeling_lora.XLMRobertaLoRA",
|
10 |
+
"AutoModelForMaskedLM": "jinaai/xlm-roberta-flash-implementation--modeling_xlm_roberta.XLMRobertaForMaskedLM",
|
11 |
+
"AutoModelForPreTraining": "jinaai/xlm-roberta-flash-implementation--modeling_xlm_roberta.XLMRobertaForPreTraining"
|
12 |
+
},
|
13 |
+
"bos_token_id": 0,
|
14 |
+
"classifier_dropout": null,
|
15 |
+
"emb_pooler": null,
|
16 |
+
"eos_token_id": 2,
|
17 |
+
"hidden_act": "gelu",
|
18 |
+
"hidden_dropout_prob": 0.1,
|
19 |
+
"hidden_size": 1024,
|
20 |
+
"initializer_range": 0.02,
|
21 |
+
"intermediate_size": 4096,
|
22 |
+
"layer_norm_eps": 1e-05,
|
23 |
+
"load_trained_adapters": true,
|
24 |
+
"lora_adaptations": [
|
25 |
+
"retrieval.query",
|
26 |
+
"retrieval.passage",
|
27 |
+
"separation",
|
28 |
+
"classification",
|
29 |
+
"text-matching"
|
30 |
+
],
|
31 |
+
"lora_alpha": 1,
|
32 |
+
"lora_dropout_p": 0.0,
|
33 |
+
"lora_main_params_trainable": false,
|
34 |
+
"lora_rank": 4,
|
35 |
+
"matryoshka_dimensions": [
|
36 |
+
32,
|
37 |
+
64,
|
38 |
+
128,
|
39 |
+
256,
|
40 |
+
512,
|
41 |
+
768,
|
42 |
+
1024
|
43 |
+
],
|
44 |
+
"max_position_embeddings": 8194,
|
45 |
+
"model_type": "xlm-roberta",
|
46 |
+
"num_attention_heads": 16,
|
47 |
+
"num_hidden_layers": 24,
|
48 |
+
"output_past": true,
|
49 |
+
"pad_token_id": 1,
|
50 |
+
"position_embedding_type": "rotary",
|
51 |
+
"rotary_emb_base": 20000.0,
|
52 |
+
"task_instructions": {
|
53 |
+
"classification": "",
|
54 |
+
"retrieval.passage": "Represent the document for retrieval: ",
|
55 |
+
"retrieval.query": "Represent the query for retrieving evidence documents: ",
|
56 |
+
"separation": "",
|
57 |
+
"text-matching": ""
|
58 |
+
},
|
59 |
+
"torch_dtype": "float32",
|
60 |
+
"transformers_version": "4.46.3",
|
61 |
+
"truncate_dim": null,
|
62 |
+
"type_vocab_size": 1,
|
63 |
+
"use_cache": false,
|
64 |
+
"use_flash_attn": false,
|
65 |
+
"use_reentrant": false,
|
66 |
+
"vocab_size": 250002
|
67 |
+
}
|
config_sentence_transformers.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"__version__": {
|
3 |
+
"sentence_transformers": "3.3.1",
|
4 |
+
"transformers": "4.46.3",
|
5 |
+
"pytorch": "2.4.0"
|
6 |
+
},
|
7 |
+
"prompts": {
|
8 |
+
"retrieval.query": "Represent the query for retrieving evidence documents: ",
|
9 |
+
"retrieval.passage": "Represent the document for retrieval: ",
|
10 |
+
"separation": "",
|
11 |
+
"classification": "",
|
12 |
+
"text-matching": ""
|
13 |
+
},
|
14 |
+
"default_prompt_name": null,
|
15 |
+
"similarity_fn_name": "cosine"
|
16 |
+
}
|
custom_st.py
ADDED
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
from io import BytesIO
|
5 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from torch import nn
|
9 |
+
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
10 |
+
|
11 |
+
logger = logging.getLogger(__name__)
|
12 |
+
|
13 |
+
|
14 |
+
class Transformer(nn.Module):
|
15 |
+
"""Huggingface AutoModel to generate token embeddings.
|
16 |
+
Loads the correct class, e.g. BERT / RoBERTa etc.
|
17 |
+
|
18 |
+
Args:
|
19 |
+
model_name_or_path: Huggingface models name
|
20 |
+
(https://huggingface.co/models)
|
21 |
+
max_seq_length: Truncate any inputs longer than max_seq_length
|
22 |
+
model_args: Keyword arguments passed to the Huggingface
|
23 |
+
Transformers model
|
24 |
+
tokenizer_args: Keyword arguments passed to the Huggingface
|
25 |
+
Transformers tokenizer
|
26 |
+
config_args: Keyword arguments passed to the Huggingface
|
27 |
+
Transformers config
|
28 |
+
cache_dir: Cache dir for Huggingface Transformers to store/load
|
29 |
+
models
|
30 |
+
do_lower_case: If true, lowercases the input (independent if the
|
31 |
+
model is cased or not)
|
32 |
+
tokenizer_name_or_path: Name or path of the tokenizer. When
|
33 |
+
None, then model_name_or_path is used
|
34 |
+
"""
|
35 |
+
|
36 |
+
save_in_root: bool = True
|
37 |
+
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
model_name_or_path: str,
|
41 |
+
max_seq_length: int = None,
|
42 |
+
model_args: Dict[str, Any] = None,
|
43 |
+
tokenizer_args: Dict[str, Any] = None,
|
44 |
+
config_args: Dict[str, Any] = None,
|
45 |
+
cache_dir: str = None,
|
46 |
+
do_lower_case: bool = False,
|
47 |
+
tokenizer_name_or_path: str = None,
|
48 |
+
**kwargs,
|
49 |
+
) -> None:
|
50 |
+
super().__init__()
|
51 |
+
self.config_keys = ["max_seq_length", "do_lower_case"]
|
52 |
+
self.do_lower_case = do_lower_case
|
53 |
+
if model_args is None:
|
54 |
+
model_args = {}
|
55 |
+
if tokenizer_args is None:
|
56 |
+
tokenizer_args = {}
|
57 |
+
if config_args is None:
|
58 |
+
config_args = {}
|
59 |
+
|
60 |
+
if kwargs.get("backend", "torch") != "torch":
|
61 |
+
logger.warning(
|
62 |
+
f'"jinaai/jina-embeddings-v3" is currently not compatible with the {kwargs["backend"]} backend. '
|
63 |
+
'Continuing with the "torch" backend.'
|
64 |
+
)
|
65 |
+
|
66 |
+
self.config = AutoConfig.from_pretrained(model_name_or_path, **config_args, cache_dir=cache_dir)
|
67 |
+
|
68 |
+
self._lora_adaptations = self.config.lora_adaptations
|
69 |
+
if (
|
70 |
+
not isinstance(self._lora_adaptations, list)
|
71 |
+
or len(self._lora_adaptations) < 1
|
72 |
+
):
|
73 |
+
raise ValueError(
|
74 |
+
f"`lora_adaptations` must be a list and contain at least one element"
|
75 |
+
)
|
76 |
+
self._adaptation_map = {
|
77 |
+
name: idx for idx, name in enumerate(self._lora_adaptations)
|
78 |
+
}
|
79 |
+
|
80 |
+
self.default_task = model_args.pop('default_task', None)
|
81 |
+
|
82 |
+
self.auto_model = AutoModel.from_pretrained(model_name_or_path, config=self.config, cache_dir=cache_dir, **model_args)
|
83 |
+
|
84 |
+
if max_seq_length is not None and "model_max_length" not in tokenizer_args:
|
85 |
+
tokenizer_args["model_max_length"] = max_seq_length
|
86 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
87 |
+
tokenizer_name_or_path if tokenizer_name_or_path is not None else model_name_or_path,
|
88 |
+
cache_dir=cache_dir,
|
89 |
+
**tokenizer_args,
|
90 |
+
)
|
91 |
+
|
92 |
+
# No max_seq_length set. Try to infer from model
|
93 |
+
if max_seq_length is None:
|
94 |
+
if (
|
95 |
+
hasattr(self.auto_model, "config")
|
96 |
+
and hasattr(self.auto_model.config, "max_position_embeddings")
|
97 |
+
and hasattr(self.tokenizer, "model_max_length")
|
98 |
+
):
|
99 |
+
max_seq_length = min(self.auto_model.config.max_position_embeddings, self.tokenizer.model_max_length)
|
100 |
+
|
101 |
+
self.max_seq_length = max_seq_length
|
102 |
+
|
103 |
+
if tokenizer_name_or_path is not None:
|
104 |
+
self.auto_model.config.tokenizer_class = self.tokenizer.__class__.__name__
|
105 |
+
|
106 |
+
|
107 |
+
@property
|
108 |
+
def default_task(self):
|
109 |
+
return self._default_task
|
110 |
+
|
111 |
+
@default_task.setter
|
112 |
+
def default_task(self, task: Union[None, str]):
|
113 |
+
self._validate_task(task)
|
114 |
+
self._default_task = task
|
115 |
+
|
116 |
+
|
117 |
+
def _validate_task(self, task: str):
|
118 |
+
if task and task not in self._lora_adaptations:
|
119 |
+
raise ValueError(
|
120 |
+
f"Unsupported task '{task}'. "
|
121 |
+
f"Supported tasks are: {', '.join(self.config.lora_adaptations)}. "
|
122 |
+
f"Alternatively, don't pass the `task` argument to disable LoRA."
|
123 |
+
)
|
124 |
+
|
125 |
+
def forward(
|
126 |
+
self, features: Dict[str, torch.Tensor], task: Optional[str] = None
|
127 |
+
) -> Dict[str, torch.Tensor]:
|
128 |
+
"""Returns token_embeddings, cls_token"""
|
129 |
+
self._validate_task(task)
|
130 |
+
task = task or self.default_task
|
131 |
+
adapter_mask = None
|
132 |
+
if task:
|
133 |
+
task_id = self._adaptation_map[task]
|
134 |
+
num_examples = features['input_ids'].size(0)
|
135 |
+
adapter_mask = torch.full(
|
136 |
+
(num_examples,), task_id, dtype=torch.int32, device=features['input_ids'].device
|
137 |
+
)
|
138 |
+
|
139 |
+
lora_arguments = (
|
140 |
+
{"adapter_mask": adapter_mask} if adapter_mask is not None else {}
|
141 |
+
)
|
142 |
+
features.pop('prompt_length', None)
|
143 |
+
output_states = self.auto_model.forward(**features, **lora_arguments, return_dict=False)
|
144 |
+
output_tokens = output_states[0]
|
145 |
+
features.update({"token_embeddings": output_tokens, "attention_mask": features["attention_mask"]})
|
146 |
+
return features
|
147 |
+
|
148 |
+
def get_word_embedding_dimension(self) -> int:
|
149 |
+
return self.auto_model.config.hidden_size
|
150 |
+
|
151 |
+
def tokenize(
|
152 |
+
self,
|
153 |
+
texts: Union[List[str], List[dict], List[Tuple[str, str]]],
|
154 |
+
padding: Union[str, bool] = True
|
155 |
+
) -> Dict[str, torch.Tensor]:
|
156 |
+
"""Tokenizes a text and maps tokens to token-ids"""
|
157 |
+
output = {}
|
158 |
+
if isinstance(texts[0], str):
|
159 |
+
to_tokenize = [texts]
|
160 |
+
elif isinstance(texts[0], dict):
|
161 |
+
to_tokenize = []
|
162 |
+
output["text_keys"] = []
|
163 |
+
for lookup in texts:
|
164 |
+
text_key, text = next(iter(lookup.items()))
|
165 |
+
to_tokenize.append(text)
|
166 |
+
output["text_keys"].append(text_key)
|
167 |
+
to_tokenize = [to_tokenize]
|
168 |
+
else:
|
169 |
+
batch1, batch2 = [], []
|
170 |
+
for text_tuple in texts:
|
171 |
+
batch1.append(text_tuple[0])
|
172 |
+
batch2.append(text_tuple[1])
|
173 |
+
to_tokenize = [batch1, batch2]
|
174 |
+
|
175 |
+
# strip
|
176 |
+
to_tokenize = [[str(s).strip() for s in col] for col in to_tokenize]
|
177 |
+
|
178 |
+
# Lowercase
|
179 |
+
if self.do_lower_case:
|
180 |
+
to_tokenize = [[s.lower() for s in col] for col in to_tokenize]
|
181 |
+
|
182 |
+
output.update(
|
183 |
+
self.tokenizer(
|
184 |
+
*to_tokenize,
|
185 |
+
padding=padding,
|
186 |
+
truncation="longest_first",
|
187 |
+
return_tensors="pt",
|
188 |
+
max_length=self.max_seq_length,
|
189 |
+
)
|
190 |
+
)
|
191 |
+
return output
|
192 |
+
|
193 |
+
def get_config_dict(self) -> Dict[str, Any]:
|
194 |
+
return {key: self.__dict__[key] for key in self.config_keys}
|
195 |
+
|
196 |
+
def save(self, output_path: str, safe_serialization: bool = True) -> None:
|
197 |
+
self.auto_model.save_pretrained(output_path, safe_serialization=safe_serialization)
|
198 |
+
self.tokenizer.save_pretrained(output_path)
|
199 |
+
|
200 |
+
with open(os.path.join(output_path, "sentence_bert_config.json"), "w") as fOut:
|
201 |
+
json.dump(self.get_config_dict(), fOut, indent=2)
|
202 |
+
|
203 |
+
|
204 |
+
@classmethod
|
205 |
+
def load(cls, input_path: str) -> "Transformer":
|
206 |
+
# Old classes used other config names than 'sentence_bert_config.json'
|
207 |
+
for config_name in [
|
208 |
+
"sentence_bert_config.json",
|
209 |
+
"sentence_roberta_config.json",
|
210 |
+
"sentence_distilbert_config.json",
|
211 |
+
"sentence_camembert_config.json",
|
212 |
+
"sentence_albert_config.json",
|
213 |
+
"sentence_xlm-roberta_config.json",
|
214 |
+
"sentence_xlnet_config.json",
|
215 |
+
]:
|
216 |
+
sbert_config_path = os.path.join(input_path, config_name)
|
217 |
+
if os.path.exists(sbert_config_path):
|
218 |
+
break
|
219 |
+
|
220 |
+
with open(sbert_config_path) as fIn:
|
221 |
+
config = json.load(fIn)
|
222 |
+
# Don't allow configs to set trust_remote_code
|
223 |
+
if "model_args" in config and "trust_remote_code" in config["model_args"]:
|
224 |
+
config["model_args"].pop("trust_remote_code")
|
225 |
+
if "tokenizer_args" in config and "trust_remote_code" in config["tokenizer_args"]:
|
226 |
+
config["tokenizer_args"].pop("trust_remote_code")
|
227 |
+
if "config_args" in config and "trust_remote_code" in config["config_args"]:
|
228 |
+
config["config_args"].pop("trust_remote_code")
|
229 |
+
return cls(model_name_or_path=input_path, **config)
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ec2a7fec4584bf58064ee4197578edc9993e4e7c6fc6adb03fc57a0088770289
|
3 |
+
size 2289306368
|
modules.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"idx": 0,
|
4 |
+
"name": "transformer",
|
5 |
+
"path": "",
|
6 |
+
"type": "custom_st.Transformer"
|
7 |
+
},
|
8 |
+
{
|
9 |
+
"idx": 1,
|
10 |
+
"name": "pooler",
|
11 |
+
"path": "1_Pooling",
|
12 |
+
"type": "sentence_transformers.models.Pooling"
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"idx": 2,
|
16 |
+
"name": "normalizer",
|
17 |
+
"path": "2_Normalize",
|
18 |
+
"type": "sentence_transformers.models.Normalize"
|
19 |
+
}
|
20 |
+
]
|
sentence_bert_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"max_seq_length": 8194,
|
3 |
+
"do_lower_case": false
|
4 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"cls_token": {
|
10 |
+
"content": "<s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"eos_token": {
|
17 |
+
"content": "</s>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"mask_token": {
|
24 |
+
"content": "<mask>",
|
25 |
+
"lstrip": true,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
},
|
30 |
+
"pad_token": {
|
31 |
+
"content": "<pad>",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": false,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false
|
36 |
+
},
|
37 |
+
"sep_token": {
|
38 |
+
"content": "</s>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false
|
43 |
+
},
|
44 |
+
"unk_token": {
|
45 |
+
"content": "<unk>",
|
46 |
+
"lstrip": false,
|
47 |
+
"normalized": false,
|
48 |
+
"rstrip": false,
|
49 |
+
"single_word": false
|
50 |
+
}
|
51 |
+
}
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3e19cd8c08f528b481e909f73dbd1fd62b1e8b1117579ba205e477801237f9e0
|
3 |
+
size 17082988
|
tokenizer_config.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "<s>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"1": {
|
12 |
+
"content": "<pad>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"2": {
|
20 |
+
"content": "</s>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"3": {
|
28 |
+
"content": "<unk>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"250001": {
|
36 |
+
"content": "<mask>",
|
37 |
+
"lstrip": true,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
}
|
43 |
+
},
|
44 |
+
"bos_token": "<s>",
|
45 |
+
"clean_up_tokenization_spaces": true,
|
46 |
+
"cls_token": "<s>",
|
47 |
+
"eos_token": "</s>",
|
48 |
+
"mask_token": "<mask>",
|
49 |
+
"model_max_length": 8194,
|
50 |
+
"pad_token": "<pad>",
|
51 |
+
"sep_token": "</s>",
|
52 |
+
"tokenizer_class": "XLMRobertaTokenizer",
|
53 |
+
"unk_token": "<unk>"
|
54 |
+
}
|