prdev commited on
Commit
634c39b
·
verified ·
1 Parent(s): e62f92a

Upload 14 files

Browse files
.ipynb_checkpoints/mteb_eval-checkpoint.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mteb
2
+ from mteb.encoder_interface import PromptType
3
+ from sentence_transformers import SentenceTransformer, models
4
+ import numpy as np
5
+ import torch
6
+ import os
7
+ import math
8
+
9
+ model_save_path = "./" #REPLACE WITH YOUR PATH
10
+
11
+ # Reload the prepared SentenceTransformer model
12
+ model = SentenceTransformer(model_save_path)
13
+
14
+ # -------- Step 3: Define Custom Model Interface for MTEB --------
15
+ class CustomModel:
16
+ def __init__(self, model):
17
+ self.model = model
18
+
19
+ def encode(
20
+ self,
21
+ sentences,
22
+ task_name: str,
23
+ prompt_type = None,
24
+ max_batch_size: int = 32, # Set default max batch size
25
+ **kwargs
26
+ ) -> np.ndarray:
27
+ """
28
+ Encodes the given sentences using the model with a maximum batch size.
29
+
30
+ Args:
31
+ sentences (List[str]): The sentences to encode.
32
+ task_name (str): The name of the task.
33
+ prompt_type (Optional[PromptType]): The prompt type to use.
34
+ max_batch_size (int): The maximum number of sentences to process in a single batch.
35
+ **kwargs: Additional arguments to pass to the encoder.
36
+
37
+ Returns:
38
+ np.ndarray: Encoded sentences as a numpy array.
39
+ """
40
+
41
+ sentences = [str(sentence) for sentence in sentences]
42
+ total_sentences = len(sentences)
43
+ num_batches = math.ceil(total_sentences / max_batch_size)
44
+ embeddings_list = []
45
+
46
+ for batch_idx in range(num_batches):
47
+ start_idx = batch_idx * max_batch_size
48
+ end_idx = min(start_idx + max_batch_size, total_sentences)
49
+ batch_sentences = sentences[start_idx:end_idx]
50
+ batch_embeddings = self.model.encode(batch_sentences, convert_to_tensor=True)
51
+
52
+ if not isinstance(batch_embeddings, torch.Tensor):
53
+ batch_embeddings = torch.tensor(batch_embeddings)
54
+
55
+ embeddings_list.append(batch_embeddings.cpu().numpy())
56
+
57
+ return np.vstack(embeddings_list)
58
+
59
+
60
+
61
+ # Wrap the SentenceTransformer model in the CustomModel class
62
+ custom_model = CustomModel(model)
63
+
64
+ # Select the MTEB tasks to evaluate
65
+ tasks = mteb.get_benchmark("MTEB(eng, classic)")
66
+
67
+ # Initialize the evaluation framework
68
+ evaluation = mteb.MTEB(tasks=tasks)
69
+
70
+ # Run evaluation and save results
71
+ results = evaluation.run(custom_model, output_folder="results/model_results")
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": true,
4
+ "pooling_mode_mean_tokens": false,
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 CHANGED
@@ -1,3 +1,141 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - sentence-transformers
4
+ - sentence-similarity
5
+ - feature-extraction
6
+ base_model: distilbert/distilbert-base-uncased
7
+ pipeline_tag: sentence-similarity
8
+ library_name: sentence-transformers
9
+ ---
10
+
11
+ # SentenceTransformer based on distilbert/distilbert-base-uncased
12
+
13
+ This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [distilbert/distilbert-base-uncased](https://huggingface.co/distilbert/distilbert-base-uncased). It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
14
+
15
+ ## Model Details
16
+
17
+ ### Model Description
18
+ - **Model Type:** Sentence Transformer
19
+ - **Base model:** [distilbert/distilbert-base-uncased](https://huggingface.co/distilbert/distilbert-base-uncased) <!-- at revision 12040accade4e8a0f71eabdb258fecc2e7e948be -->
20
+ - **Maximum Sequence Length:** 512 tokens
21
+ - **Output Dimensionality:** 768 dimensions
22
+ - **Similarity Function:** Cosine Similarity
23
+ <!-- - **Training Dataset:** Unknown -->
24
+ <!-- - **Language:** Unknown -->
25
+ <!-- - **License:** Unknown -->
26
+
27
+ ### Model Sources
28
+
29
+ - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
30
+ - **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
31
+ - **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
32
+
33
+ ### Full Model Architecture
34
+
35
+ ```
36
+ SentenceTransformer(
37
+ (0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: DistilBertModel
38
+ (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
39
+ )
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ### Direct Usage (Sentence Transformers)
45
+
46
+ First install the Sentence Transformers library:
47
+
48
+ ```bash
49
+ pip install -U sentence-transformers
50
+ ```
51
+
52
+ Then you can load this model and run inference.
53
+ ```python
54
+ from sentence_transformers import SentenceTransformer
55
+
56
+ # Download from the 🤗 Hub
57
+ model = SentenceTransformer("sentence_transformers_model_id")
58
+ # Run inference
59
+ sentences = [
60
+ 'The weather is lovely today.',
61
+ "It's so sunny outside!",
62
+ 'He drove to the stadium.',
63
+ ]
64
+ embeddings = model.encode(sentences)
65
+ print(embeddings.shape)
66
+ # [3, 768]
67
+
68
+ # Get the similarity scores for the embeddings
69
+ similarities = model.similarity(embeddings, embeddings)
70
+ print(similarities.shape)
71
+ # [3, 3]
72
+ ```
73
+
74
+ <!--
75
+ ### Direct Usage (Transformers)
76
+
77
+ <details><summary>Click to see the direct usage in Transformers</summary>
78
+
79
+ </details>
80
+ -->
81
+
82
+ <!--
83
+ ### Downstream Usage (Sentence Transformers)
84
+
85
+ You can finetune this model on your own dataset.
86
+
87
+ <details><summary>Click to expand</summary>
88
+
89
+ </details>
90
+ -->
91
+
92
+ <!--
93
+ ### Out-of-Scope Use
94
+
95
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
96
+ -->
97
+
98
+ <!--
99
+ ## Bias, Risks and Limitations
100
+
101
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
102
+ -->
103
+
104
+ <!--
105
+ ### Recommendations
106
+
107
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
108
+ -->
109
+
110
+ ## Training Details
111
+
112
+ ### Framework Versions
113
+ - Python: 3.10.12
114
+ - Sentence Transformers: 3.3.1
115
+ - Transformers: 4.48.0.dev0
116
+ - PyTorch: 2.1.0a0+32f93b1
117
+ - Accelerate: 1.2.0
118
+ - Datasets: 2.21.0
119
+ - Tokenizers: 0.21.0
120
+
121
+ ## Citation
122
+
123
+ ### BibTeX
124
+
125
+ <!--
126
+ ## Glossary
127
+
128
+ *Clearly define terms in order to be accessible across audiences.*
129
+ -->
130
+
131
+ <!--
132
+ ## Model Card Authors
133
+
134
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
135
+ -->
136
+
137
+ <!--
138
+ ## Model Card Contact
139
+
140
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
141
+ -->
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "distilbert-base-uncased",
3
+ "activation": "gelu",
4
+ "architectures": [
5
+ "DistilBertModel"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "dim": 768,
9
+ "dropout": 0.1,
10
+ "hidden_dim": 3072,
11
+ "initializer_range": 0.02,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "distilbert",
14
+ "n_heads": 12,
15
+ "n_layers": 6,
16
+ "pad_token_id": 0,
17
+ "qa_dropout": 0.1,
18
+ "seq_classif_dropout": 0.2,
19
+ "sinusoidal_pos_embds": false,
20
+ "tie_weights_": true,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.48.0.dev0",
23
+ "vocab_size": 30522
24
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "3.3.1",
4
+ "transformers": "4.48.0.dev0",
5
+ "pytorch": "2.1.0a0+32f93b1"
6
+ },
7
+ "prompts": {},
8
+ "default_prompt_name": null,
9
+ "similarity_fn_name": "cosine"
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abaa3ca6ba670db88b0d70cf33d5545e3b45f7cb03d620accf05c7bc8974ea51
3
+ size 265462608
model_card.md ADDED
The diff for this file is too large to render. See raw diff
 
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_eval.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mteb
2
+ from mteb.encoder_interface import PromptType
3
+ from sentence_transformers import SentenceTransformer, models
4
+ import numpy as np
5
+ import torch
6
+ import os
7
+ import math
8
+
9
+ model_save_path = "./" #REPLACE WITH YOUR PATH
10
+
11
+ # Reload the prepared SentenceTransformer model
12
+ model = SentenceTransformer(model_save_path)
13
+
14
+ # -------- Step 3: Define Custom Model Interface for MTEB --------
15
+ class CustomModel:
16
+ def __init__(self, model):
17
+ self.model = model
18
+
19
+ def encode(
20
+ self,
21
+ sentences,
22
+ task_name: str,
23
+ prompt_type = None,
24
+ max_batch_size: int = 32, # Set default max batch size
25
+ **kwargs
26
+ ) -> np.ndarray:
27
+ """
28
+ Encodes the given sentences using the model with a maximum batch size.
29
+
30
+ Args:
31
+ sentences (List[str]): The sentences to encode.
32
+ task_name (str): The name of the task.
33
+ prompt_type (Optional[PromptType]): The prompt type to use.
34
+ max_batch_size (int): The maximum number of sentences to process in a single batch.
35
+ **kwargs: Additional arguments to pass to the encoder.
36
+
37
+ Returns:
38
+ np.ndarray: Encoded sentences as a numpy array.
39
+ """
40
+
41
+ sentences = [str(sentence) for sentence in sentences]
42
+ total_sentences = len(sentences)
43
+ num_batches = math.ceil(total_sentences / max_batch_size)
44
+ embeddings_list = []
45
+
46
+ for batch_idx in range(num_batches):
47
+ start_idx = batch_idx * max_batch_size
48
+ end_idx = min(start_idx + max_batch_size, total_sentences)
49
+ batch_sentences = sentences[start_idx:end_idx]
50
+ batch_embeddings = self.model.encode(batch_sentences, convert_to_tensor=True)
51
+
52
+ if not isinstance(batch_embeddings, torch.Tensor):
53
+ batch_embeddings = torch.tensor(batch_embeddings)
54
+
55
+ embeddings_list.append(batch_embeddings.cpu().numpy())
56
+
57
+ return np.vstack(embeddings_list)
58
+
59
+
60
+
61
+ # Wrap the SentenceTransformer model in the CustomModel class
62
+ custom_model = CustomModel(model)
63
+
64
+ # Select the MTEB tasks to evaluate
65
+ tasks = mteb.get_benchmark("MTEB(eng, classic)")
66
+
67
+ # Initialize the evaluation framework
68
+ evaluation = mteb.MTEB(tasks=tasks)
69
+
70
+ # Run evaluation and save results
71
+ results = evaluation.run(custom_model, output_folder="results/model_results")
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,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "extra_special_tokens": {},
48
+ "mask_token": "[MASK]",
49
+ "model_max_length": 512,
50
+ "pad_token": "[PAD]",
51
+ "sep_token": "[SEP]",
52
+ "strip_accents": null,
53
+ "tokenize_chinese_chars": true,
54
+ "tokenizer_class": "DistilBertTokenizer",
55
+ "unk_token": "[UNK]"
56
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff