sionic commited on
Commit
b401e88
1 Parent(s): 376f6e4

Upload a code to evaluate MTEB

Browse files
Files changed (2) hide show
  1. model_api.py +40 -0
  2. mteb_evaluate.py +53 -0
model_api.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional, Union
2
+
3
+ import numpy as np
4
+ import requests
5
+ from mteb import DRESModel
6
+ from tqdm import tqdm
7
+
8
+
9
+ class ModelV1(DRESModel):
10
+ def __init__(self, url: str, instruction: Optional[str] = None, batch_size: int = 128, **kwargs) -> None:
11
+ self.url = url
12
+ self.instruction = instruction
13
+ self.batch_size = batch_size
14
+
15
+ def get_embeddings(self, queries: List[str]) -> np.ndarray:
16
+ return np.asarray(
17
+ requests.post(self.url, json={'inputs': queries}).json()['embedding'],
18
+ dtype=np.float32,
19
+ ).reshape(len(queries), 2048)
20
+
21
+ def encode_queries(self, queries: List[str], **kwargs) -> np.ndarray:
22
+ return self.encode([f'{self.instruction}{query}' for query in queries])
23
+
24
+ def encode_corpus(self, corpus: List[Union[Dict[str, str], str]], **kwargs) -> np.ndarray:
25
+ sentences: List[str] = (
26
+ [f"{doc.get('title', '')} {doc['text']}".strip() for doc in corpus]
27
+ if isinstance(corpus[0], dict)
28
+ else corpus
29
+ )
30
+
31
+ return self.encode(sentences)
32
+
33
+ def encode(self, sentences: List[str], **kwargs) -> np.ndarray:
34
+ return np.concatenate(
35
+ [
36
+ self.get_embeddings(sentences[idx:idx + self.batch_size])
37
+ for idx in tqdm(range(0, len(sentences), self.batch_size), desc='encode')
38
+ ],
39
+ axis=0,
40
+ )
mteb_evaluate.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser, Namespace
2
+ from typing import List, Optional
3
+
4
+ from model_api import ModelV1
5
+ from mteb import MTEB
6
+
7
+ RETRIEVAL_TASKS: List[str] = [
8
+ 'ArguAna',
9
+ 'ClimateFEVER',
10
+ 'DBPedia',
11
+ 'FEVER',
12
+ 'FiQA2018',
13
+ 'HotpotQA',
14
+ 'MSMARCO',
15
+ 'NFCorpus',
16
+ 'NQ',
17
+ 'QuoraRetrieval',
18
+ 'SCIDOCS',
19
+ 'SciFact',
20
+ 'Touche2020',
21
+ 'TRECCOVID',
22
+ ]
23
+
24
+
25
+ def get_arguments() -> Namespace:
26
+ parser = ArgumentParser()
27
+ parser.add_argument('--url', type=str, default='https://api.sionic.ai/v1/embedding', help='api server url')
28
+ parser.add_argument('--instruction', type=str, default='query: ', help='query instruction')
29
+ parser.add_argument('--batch_size', type=int, default=128)
30
+ parser.add_argument('--output_dir', type=str, default='./result/v1')
31
+ return parser.parse_args()
32
+
33
+
34
+ if __name__ == '__main__':
35
+ args = get_arguments()
36
+
37
+ model = ModelV1(url=args.url, instruction=args.instruction, batch_size=args.batch_size)
38
+
39
+ task_names: List[str] = [t.description['name'] for t in MTEB(task_types=None, task_langs=['en']).tasks]
40
+
41
+ for task in task_names:
42
+ if task in ['MSMARCOv2']:
43
+ continue
44
+
45
+ instruction: Optional[str] = args.instruction if ('CQADupstack' in task) or (task in RETRIEVAL_TASKS) else None
46
+ model.instruction = instruction
47
+
48
+ evaluation = MTEB(
49
+ tasks=[task],
50
+ task_langs=['en'],
51
+ eval_splits=['test' if task not in ['MSMARCO'] else 'dev'],
52
+ )
53
+ evaluation.run(model, output_folder=args.output_dir)