angelitasr commited on
Commit
9e3ac21
·
verified ·
1 Parent(s): bad860f

End of training

Browse files
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,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - sentence-transformers
4
+ - sentence-similarity
5
+ - feature-extraction
6
+ - generated_from_trainer
7
+ - dataset_size:3503
8
+ - loss:MultipleNegativesRankingLoss
9
+ base_model: jinaai/jina-embeddings-v3
10
+ widget:
11
+ - source_sentence: '###Question###:Factorising into a Double Bracket-Factorise a quadratic
12
+ expression in the form x² + bx - c-If
13
+
14
+ \(
15
+
16
+ m^{2}+5 m-14 \equiv(m+a)(m+b)
17
+
18
+ \)
19
+
20
+ then \( a \times b= \)
21
+
22
+ ###Correct Answer###:\( -14 \)
23
+
24
+ ###Misconcepted Incorrect answer###:\( 5 \)'
25
+ sentences:
26
+ - Does not know that units of volume are usually cubed
27
+ - Believes the coefficent of x in an expanded quadratic comes from multiplying the
28
+ two numbers in the brackets
29
+ - Does not copy a given method accurately
30
+ - source_sentence: '###Question###:Rounding to the Nearest Whole (10, 100, etc)-Round
31
+ non-integers to the nearest 10-What is \( \mathbf{8 6 9 8 . 9} \) rounded to the
32
+ nearest ten?
33
+
34
+ ###Correct Answer###:\( 8700 \)
35
+
36
+ ###Misconcepted Incorrect answer###:\( 8699 \)'
37
+ sentences:
38
+ - Rounds to the wrong degree of accuracy (rounds too much)
39
+ - 'Believes division is commutative '
40
+ - Believes that a number divided by itself equals 0
41
+ - source_sentence: '###Question###:Simultaneous Equations-Solve linear simultaneous
42
+ equations requiring a scaling of both expressions-If five cups of tea and two
43
+ cups of coffee cost \( £ 3.70 \), and two cups of tea and five cups of coffee
44
+ cost \( £ 4.00 \), what is the cost of a cup of tea and a cup of coffee?
45
+
46
+ ###Correct Answer###:Tea \( =50 \mathrm{p} \) coffee \( =60 p \)
47
+
48
+ ###Misconcepted Incorrect answer###:\( \begin{array}{l}\text { Tea }=0.5 \\ \text
49
+ { coffee }=0.6\end{array} \)'
50
+ sentences:
51
+ - Misinterprets the meaning of angles on a straight line angle fact
52
+ - Does not include units in answer.
53
+ - Believes midpoint calculation is just half of the difference
54
+ - source_sentence: '###Question###:Quadratic Sequences-Find the nth term rule for
55
+ ascending quadratic sequences in the form ax² + bx + c-\(
56
+
57
+ 6,14,28,48,74, \ldots
58
+
59
+ \)
60
+
61
+
62
+ When calculating the nth-term rule of this sequence, what should replace the triangle?
63
+
64
+
65
+ nth-term rule: \( 3 n^{2} \)\( \color{red}\triangle \) \(n\) \( \color{purple}\square
66
+ \)
67
+
68
+
69
+ ###Correct Answer###:\( -1 \)
70
+
71
+ (or just a - sign)
72
+
73
+ ###Misconcepted Incorrect answer###:\[
74
+
75
+ +1
76
+
77
+ \]
78
+
79
+ (or just a + sign)'
80
+ sentences:
81
+ - 'When finding the differences between terms in a sequence, believes they can do
82
+ so from right to left '
83
+ - When solving an equation forgets to eliminate the coefficient in front of the
84
+ variable in the last step
85
+ - Believes parallelogram is the term used to describe two lines at right angles
86
+ - source_sentence: '###Question###:Written Multiplication-Multiply 2 digit integers
87
+ by 2 digit integers using long multiplication-Which working out is correct for
88
+ $72 \times 36$?
89
+
90
+ ###Correct Answer###:![ Long multiplication for 72 multiplied by 36 with correct
91
+ working and correct final answer. First row of working is correct: 4 3 2. Second
92
+ row of working is correct: 2 1 6 0. Final answer is correct: 2 5 9 2.]()
93
+
94
+ ###Misconcepted Incorrect answer###:![ Long multiplication for 72 multiplied by
95
+ 36 with incorrect working and incorrect final answer. First row of working is
96
+ incorrect: 4 2 2. Second row of working is incorrect: 2 7. Final answer is incorrect:
97
+ 4 4 9.]()'
98
+ sentences:
99
+ - When solving an equation forgets to eliminate the coefficient in front of the
100
+ variable in the last step
101
+ - Thinks a variable next to a number means addition rather than multiplication
102
+ - When two digits multiply to 10 or more during a multiplication problem, does not
103
+ add carried value to the preceding digit
104
+ pipeline_tag: sentence-similarity
105
+ library_name: sentence-transformers
106
+ ---
107
+
108
+ # SentenceTransformer based on jinaai/jina-embeddings-v3
109
+
110
+ 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.
111
+
112
+ ## Model Details
113
+
114
+ ### Model Description
115
+ - **Model Type:** Sentence Transformer
116
+ - **Base model:** [jinaai/jina-embeddings-v3](https://huggingface.co/jinaai/jina-embeddings-v3) <!-- at revision 62a81741b58448ed8f691764cec7aa5d3c045e4c -->
117
+ - **Maximum Sequence Length:** 8194 tokens
118
+ - **Output Dimensionality:** 1024 tokens
119
+ - **Similarity Function:** Cosine Similarity
120
+ <!-- - **Training Dataset:** Unknown -->
121
+ <!-- - **Language:** Unknown -->
122
+ <!-- - **License:** Unknown -->
123
+
124
+ ### Model Sources
125
+
126
+ - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
127
+ - **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
128
+ - **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
129
+
130
+ ### Full Model Architecture
131
+
132
+ ```
133
+ SentenceTransformer(
134
+ (transformer): Transformer(
135
+ (auto_model): XLMRobertaLoRA(
136
+ (roberta): XLMRobertaModel(
137
+ (embeddings): XLMRobertaEmbeddings(
138
+ (word_embeddings): ParametrizedEmbedding(
139
+ 250002, 1024, padding_idx=1
140
+ (parametrizations): ModuleDict(
141
+ (weight): ParametrizationList(
142
+ (0): LoRAParametrization()
143
+ )
144
+ )
145
+ )
146
+ (token_type_embeddings): ParametrizedEmbedding(
147
+ 1, 1024
148
+ (parametrizations): ModuleDict(
149
+ (weight): ParametrizationList(
150
+ (0): LoRAParametrization()
151
+ )
152
+ )
153
+ )
154
+ )
155
+ (emb_drop): Dropout(p=0.1, inplace=False)
156
+ (emb_ln): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
157
+ (encoder): XLMRobertaEncoder(
158
+ (layers): ModuleList(
159
+ (0-23): 24 x Block(
160
+ (mixer): MHA(
161
+ (rotary_emb): RotaryEmbedding()
162
+ (Wqkv): ParametrizedLinearResidual(
163
+ in_features=1024, out_features=3072, bias=True
164
+ (parametrizations): ModuleDict(
165
+ (weight): ParametrizationList(
166
+ (0): LoRAParametrization()
167
+ )
168
+ )
169
+ )
170
+ (inner_attn): FlashSelfAttention(
171
+ (drop): Dropout(p=0.1, inplace=False)
172
+ )
173
+ (inner_cross_attn): FlashCrossAttention(
174
+ (drop): Dropout(p=0.1, inplace=False)
175
+ )
176
+ (out_proj): ParametrizedLinear(
177
+ in_features=1024, out_features=1024, bias=True
178
+ (parametrizations): ModuleDict(
179
+ (weight): ParametrizationList(
180
+ (0): LoRAParametrization()
181
+ )
182
+ )
183
+ )
184
+ )
185
+ (dropout1): Dropout(p=0.1, inplace=False)
186
+ (drop_path1): StochasticDepth(p=0.0, mode=row)
187
+ (norm1): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
188
+ (mlp): Mlp(
189
+ (fc1): ParametrizedLinear(
190
+ in_features=1024, out_features=4096, bias=True
191
+ (parametrizations): ModuleDict(
192
+ (weight): ParametrizationList(
193
+ (0): LoRAParametrization()
194
+ )
195
+ )
196
+ )
197
+ (fc2): ParametrizedLinear(
198
+ in_features=4096, out_features=1024, bias=True
199
+ (parametrizations): ModuleDict(
200
+ (weight): ParametrizationList(
201
+ (0): LoRAParametrization()
202
+ )
203
+ )
204
+ )
205
+ )
206
+ (dropout2): Dropout(p=0.1, inplace=False)
207
+ (drop_path2): StochasticDepth(p=0.0, mode=row)
208
+ (norm2): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)
209
+ )
210
+ )
211
+ )
212
+ (pooler): XLMRobertaPooler(
213
+ (dense): ParametrizedLinear(
214
+ in_features=1024, out_features=1024, bias=True
215
+ (parametrizations): ModuleDict(
216
+ (weight): ParametrizationList(
217
+ (0): LoRAParametrization()
218
+ )
219
+ )
220
+ )
221
+ (activation): Tanh()
222
+ )
223
+ )
224
+ )
225
+ )
226
+ (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})
227
+ (normalizer): Normalize()
228
+ )
229
+ ```
230
+
231
+ ## Usage
232
+
233
+ ### Direct Usage (Sentence Transformers)
234
+
235
+ First install the Sentence Transformers library:
236
+
237
+ ```bash
238
+ pip install -U sentence-transformers
239
+ ```
240
+
241
+ Then you can load this model and run inference.
242
+ ```python
243
+ from sentence_transformers import SentenceTransformer
244
+
245
+ # Download from the 🤗 Hub
246
+ model = SentenceTransformer("sentence_transformers_model_id")
247
+ # Run inference
248
+ sentences = [
249
+ '###Question###:Written Multiplication-Multiply 2 digit integers by 2 digit integers using long multiplication-Which working out is correct for $72 \\times 36$?\n###Correct Answer###:![ Long multiplication for 72 multiplied by 36 with correct working and correct final answer. First row of working is correct: 4 3 2. Second row of working is correct: 2 1 6 0. Final answer is correct: 2 5 9 2.]()\n###Misconcepted Incorrect answer###:![ Long multiplication for 72 multiplied by 36 with incorrect working and incorrect final answer. First row of working is incorrect: 4 2 2. Second row of working is incorrect: 2 7. Final answer is incorrect: 4 4 9.]()',
250
+ 'When two digits multiply to 10 or more during a multiplication problem, does not add carried value to the preceding digit',
251
+ 'Thinks a variable next to a number means addition rather than multiplication',
252
+ ]
253
+ embeddings = model.encode(sentences)
254
+ print(embeddings.shape)
255
+ # [3, 1024]
256
+
257
+ # Get the similarity scores for the embeddings
258
+ similarities = model.similarity(embeddings, embeddings)
259
+ print(similarities.shape)
260
+ # [3, 3]
261
+ ```
262
+
263
+ <!--
264
+ ### Direct Usage (Transformers)
265
+
266
+ <details><summary>Click to see the direct usage in Transformers</summary>
267
+
268
+ </details>
269
+ -->
270
+
271
+ <!--
272
+ ### Downstream Usage (Sentence Transformers)
273
+
274
+ You can finetune this model on your own dataset.
275
+
276
+ <details><summary>Click to expand</summary>
277
+
278
+ </details>
279
+ -->
280
+
281
+ <!--
282
+ ### Out-of-Scope Use
283
+
284
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
285
+ -->
286
+
287
+ <!--
288
+ ## Bias, Risks and Limitations
289
+
290
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
291
+ -->
292
+
293
+ <!--
294
+ ### Recommendations
295
+
296
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
297
+ -->
298
+
299
+ ## Training Details
300
+
301
+ ### Training Dataset
302
+
303
+ #### Unnamed Dataset
304
+
305
+
306
+ * Size: 3,503 training samples
307
+ * Columns: <code>anchor</code> and <code>positive</code>
308
+ * Approximate statistics based on the first 1000 samples:
309
+ | | anchor | positive |
310
+ |:--------|:-------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------|
311
+ | type | string | string |
312
+ | details | <ul><li>min: 59 tokens</li><li>mean: 131.26 tokens</li><li>max: 449 tokens</li></ul> | <ul><li>min: 6 tokens</li><li>mean: 17.43 tokens</li><li>max: 46 tokens</li></ul> |
313
+ * Samples:
314
+ | anchor | positive |
315
+ |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------|
316
+ | <code>###Question###:Area of Simple Shapes-Calculate the area of a parallelogram where the dimensions are given in the same units-What is the area of this shape? ![A parallelogram drawn on a square grid in purple with an area of 9 square units. The base is length 3 squares and the perpendicular height is also length 3 squares.]()<br>###Correct Answer###:\( 9 \)<br>###Misconcepted Incorrect answer###:\( 12 \)</code> | <code>Counts half-squares as full squares when calculating area on a square grid</code> |
317
+ | <code>###Question###:Substitution into Formula-Substitute into simple formulae given in words-A theme park charges \( £ 8 \) entry fee and then \( £ 3 \) for every ride you go on.<br>Heena goes on \( 5 \) rides.<br>How much does she pay in total?<br>###Correct Answer###:\( £ 23 \)<br>###Misconcepted Incorrect answer###:\( £ 55 \)</code> | <code>Combines variables with constants when writing a formula from a given situation</code> |
318
+ | <code>###Question###:Trial and Improvement and Iterative Methods-Use area to write algebraic expressions-The area of the rectangle on the right is \( 8 \mathrm{~cm}^{2} \).<br><br>Which of the following equations can we write from the information given? ![A rectangle with the short side labelled \(x\) and the opposite side labelled \(x^2 + 9\).]()<br>###Correct Answer###:\( x^{3}+9 x=8 \)<br>###Misconcepted Incorrect answer###:\( x^{3}+9=8 \)</code> | <code>Only multiplies the first term in the expansion of a bracket</code> |
319
+ * Loss: [<code>MultipleNegativesRankingLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#multiplenegativesrankingloss) with these parameters:
320
+ ```json
321
+ {
322
+ "scale": 20.0,
323
+ "similarity_fct": "cos_sim"
324
+ }
325
+ ```
326
+
327
+ ### Training Hyperparameters
328
+ #### Non-Default Hyperparameters
329
+
330
+ - `push_to_hub`: 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`: no
339
+ - `prediction_loss_only`: True
340
+ - `per_device_train_batch_size`: 8
341
+ - `per_device_eval_batch_size`: 8
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`: 3
354
+ - `max_steps`: -1
355
+ - `lr_scheduler_type`: linear
356
+ - `lr_scheduler_kwargs`: {}
357
+ - `warmup_ratio`: 0.0
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`: False
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`: True
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
+ - `eval_do_concat_batches`: True
424
+ - `fp16_backend`: auto
425
+ - `push_to_hub_model_id`: None
426
+ - `push_to_hub_organization`: None
427
+ - `mp_parameters`:
428
+ - `auto_find_batch_size`: False
429
+ - `full_determinism`: False
430
+ - `torchdynamo`: None
431
+ - `ray_scope`: last
432
+ - `ddp_timeout`: 1800
433
+ - `torch_compile`: False
434
+ - `torch_compile_backend`: None
435
+ - `torch_compile_mode`: None
436
+ - `dispatch_batches`: None
437
+ - `split_batches`: None
438
+ - `include_tokens_per_second`: False
439
+ - `include_num_input_tokens_seen`: False
440
+ - `neftune_noise_alpha`: None
441
+ - `optim_target_modules`: None
442
+ - `batch_eval_metrics`: False
443
+ - `eval_on_start`: False
444
+ - `use_liger_kernel`: False
445
+ - `eval_use_gather_object`: False
446
+ - `batch_sampler`: no_duplicates
447
+ - `multi_dataset_batch_sampler`: proportional
448
+
449
+ </details>
450
+
451
+ ### Training Logs
452
+ | Epoch | Step | Training Loss |
453
+ |:------:|:----:|:-------------:|
454
+ | 1.1416 | 500 | 0.317 |
455
+ | 2.2831 | 1000 | 0.0988 |
456
+
457
+
458
+ ### Framework Versions
459
+ - Python: 3.10.12
460
+ - Sentence Transformers: 3.1.1
461
+ - Transformers: 4.45.2
462
+ - PyTorch: 2.5.1+cu121
463
+ - Accelerate: 1.1.1
464
+ - Datasets: 3.1.0
465
+ - Tokenizers: 0.20.3
466
+
467
+ ## Citation
468
+
469
+ ### BibTeX
470
+
471
+ #### Sentence Transformers
472
+ ```bibtex
473
+ @inproceedings{reimers-2019-sentence-bert,
474
+ title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
475
+ author = "Reimers, Nils and Gurevych, Iryna",
476
+ booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
477
+ month = "11",
478
+ year = "2019",
479
+ publisher = "Association for Computational Linguistics",
480
+ url = "https://arxiv.org/abs/1908.10084",
481
+ }
482
+ ```
483
+
484
+ #### MultipleNegativesRankingLoss
485
+ ```bibtex
486
+ @misc{henderson2017efficient,
487
+ title={Efficient Natural Language Response Suggestion for Smart Reply},
488
+ author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
489
+ year={2017},
490
+ eprint={1705.00652},
491
+ archivePrefix={arXiv},
492
+ primaryClass={cs.CL}
493
+ }
494
+ ```
495
+
496
+ <!--
497
+ ## Glossary
498
+
499
+ *Clearly define terms in order to be accessible across audiences.*
500
+ -->
501
+
502
+ <!--
503
+ ## Model Card Authors
504
+
505
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
506
+ -->
507
+
508
+ <!--
509
+ ## Model Card Contact
510
+
511
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
512
+ -->
config_sentence_transformers.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "3.1.1",
4
+ "transformers": "4.45.2",
5
+ "pytorch": "2.5.1+cu121"
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)
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
+ }