xiaowenbin
commited on
Commit
•
2954620
1
Parent(s):
8fa4182
Upload mteb_eval_openai.py
Browse files- mteb_eval_openai.py +175 -0
mteb_eval_openai.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import time
|
4 |
+
import hashlib
|
5 |
+
import numpy as np
|
6 |
+
import requests
|
7 |
+
|
8 |
+
import logging
|
9 |
+
import functools
|
10 |
+
import tiktoken
|
11 |
+
from tqdm import tqdm
|
12 |
+
from mteb import MTEB
|
13 |
+
#from sentence_transformers import SentenceTransformer
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
logger = logging.getLogger("main")
|
16 |
+
|
17 |
+
all_task_list = ['Classification', 'Clustering', 'Reranking', 'Retrieval', 'STS', 'PairClassification']
|
18 |
+
if len(sys.argv) > 1:
|
19 |
+
task_list = [t for t in sys.argv[1].split(',') if t in all_task_list]
|
20 |
+
else:
|
21 |
+
task_list = all_task_list
|
22 |
+
|
23 |
+
OPENAI_BASE_URL = os.environ.get('OPENAI_BASE_URL', '')
|
24 |
+
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')
|
25 |
+
EMB_CACHE_DIR = os.environ.get('EMB_CACHE_DIR', '.cache/embs')
|
26 |
+
REQ_OPENAI_TIMEOUT = int(os.environ.get('REQ_OPENAI_TIMEOUT', 120))
|
27 |
+
REQ_OPENAI_RETRY = int(os.environ.get('REQ_OPENAI_RETRY', 3))
|
28 |
+
REQ_OPENAI_INTERVAL = int(os.environ.get('REQ_OPENAI_INTERVAL', 60))
|
29 |
+
os.makedirs(EMB_CACHE_DIR, exist_ok=True)
|
30 |
+
|
31 |
+
def log(*args):
|
32 |
+
print(*args, file=sys.stderr)
|
33 |
+
|
34 |
+
def uuid_for_text(text):
|
35 |
+
return hashlib.md5(text.encode('utf8')).hexdigest()
|
36 |
+
|
37 |
+
def count_openai_tokens(text, model="text-embedding-3-large"):
|
38 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
39 |
+
#encoding = tiktoken.encoding_for_model(model)
|
40 |
+
input_ids = encoding.encode(text)
|
41 |
+
return len(input_ids)
|
42 |
+
|
43 |
+
def request_openai_emb(texts, model="text-embedding-3-large",
|
44 |
+
base_url='https://api.openai.com', prefix_url='/v1/embeddings',
|
45 |
+
timeout=4, retry=3, interval=2, caching=True):
|
46 |
+
if isinstance(texts, str):
|
47 |
+
texts = [texts]
|
48 |
+
|
49 |
+
data = []
|
50 |
+
if caching:
|
51 |
+
for text in texts:
|
52 |
+
emb_file = f"{EMB_CACHE_DIR}/{uuid_for_text(text)}"
|
53 |
+
if os.path.isfile(emb_file) and os.path.getsize(emb_file) > 0:
|
54 |
+
data.append(np.loadtxt(emb_file))
|
55 |
+
if len(texts) == len(data):
|
56 |
+
return data
|
57 |
+
|
58 |
+
url = f"{OPENAI_BASE_URL}{prefix_url}" if OPENAI_BASE_URL else f"{base_url}{prefix_url}"
|
59 |
+
headers = {
|
60 |
+
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
61 |
+
"Content-Type": "application/json"
|
62 |
+
}
|
63 |
+
payload = {"input": texts, "model": model}
|
64 |
+
|
65 |
+
data = []
|
66 |
+
while retry > 0 and len(data) == 0:
|
67 |
+
try:
|
68 |
+
r = requests.post(url, headers=headers, json=payload,
|
69 |
+
timeout=timeout)
|
70 |
+
res = r.json()
|
71 |
+
for x in res["data"]:
|
72 |
+
data.append(np.array(x["embedding"]))
|
73 |
+
except Exception as e:
|
74 |
+
log(f"request openai, retry {retry}, error: {e}")
|
75 |
+
time.sleep(interval)
|
76 |
+
retry -= 1
|
77 |
+
|
78 |
+
if len(data) != len(texts):
|
79 |
+
log(f"request openai, failed, texts and embs DONT match!")
|
80 |
+
return []
|
81 |
+
|
82 |
+
if caching and len(data) > 0:
|
83 |
+
for text, emb in zip(texts, data):
|
84 |
+
emb_file = f"{EMB_CACHE_DIR}/{uuid_for_text(text)}"
|
85 |
+
np.savetxt(emb_file, emb)
|
86 |
+
|
87 |
+
return data
|
88 |
+
|
89 |
+
|
90 |
+
class OpenaiEmbModel:
|
91 |
+
|
92 |
+
def __init__(self, model_name, model_dim, *args, **kwargs):
|
93 |
+
super().__init__(*args, **kwargs)
|
94 |
+
self.model_name = model_name
|
95 |
+
self.model_dim = model_dim
|
96 |
+
|
97 |
+
def encode(self, sentences, batch_size=32, **kwargs):
|
98 |
+
i = 0
|
99 |
+
max_tokens = kwargs.get("max_tokens", 8000)
|
100 |
+
batch_tokens = 0
|
101 |
+
batch = []
|
102 |
+
batch_list = []
|
103 |
+
while i < len(sentences):
|
104 |
+
num_tokens = count_openai_tokens(sentences[i],
|
105 |
+
model=self.model_name)
|
106 |
+
if batch_tokens+num_tokens > max_tokens:
|
107 |
+
if batch:
|
108 |
+
batch_list.append(batch)
|
109 |
+
if num_tokens > max_tokens:
|
110 |
+
batch = [sentences[i][:2048]]
|
111 |
+
batch_tokens = count_openai_tokens(sentences[i][:2048],
|
112 |
+
model=self.model_name)
|
113 |
+
else:
|
114 |
+
batch = [sentences[i]]
|
115 |
+
batch_tokens = num_tokens
|
116 |
+
else:
|
117 |
+
batch_list.append([sentences[i][:2048]])
|
118 |
+
else:
|
119 |
+
batch.append(sentences[i])
|
120 |
+
batch_tokens += num_tokens
|
121 |
+
i += 1
|
122 |
+
if batch:
|
123 |
+
batch_list.append(batch)
|
124 |
+
|
125 |
+
#batch_size = min(64, batch_size)
|
126 |
+
#
|
127 |
+
#for i in range(0, len(sentences), batch_size):
|
128 |
+
# batch_texts = sentences[i:i+batch_size]
|
129 |
+
# batch_list.append(batch_texts)
|
130 |
+
|
131 |
+
log(f"Total sentences={len(sentences)}, batches={len(batch_list)}")
|
132 |
+
embs = []
|
133 |
+
waiting = 0
|
134 |
+
for batch_idx, batch_texts in enumerate(tqdm(batch_list)):
|
135 |
+
batch_embs = request_openai_emb(batch_texts, model=self.model_name,
|
136 |
+
caching=kwargs.get("caching", True),
|
137 |
+
timeout=kwargs.get("timeout", REQ_OPENAI_TIMEOUT),
|
138 |
+
retry=kwargs.get("retry", REQ_OPENAI_RETRY),
|
139 |
+
interval=kwargs.get("interval", REQ_OPENAI_INTERVAL))
|
140 |
+
|
141 |
+
if len(batch_texts) == len(batch_embs):
|
142 |
+
embs.extend(batch_embs)
|
143 |
+
waiting = waiting // 2
|
144 |
+
log(f"The batch-{batch_idx} encoding SUCCESS! waiting={waiting}s...")
|
145 |
+
else:
|
146 |
+
embs.extend([np.array([0.0 for j in range(self.model_dim)]) for i in range(len(batch_texts))])
|
147 |
+
waiting = 120 if waiting <= 0 else waiting+120
|
148 |
+
log(f"The batch-{batch_idx} encoding FAILED {len(batch_texts)}:{len(batch_embs)}! waiting={waiting}s...")
|
149 |
+
|
150 |
+
if waiting > 3600:
|
151 |
+
log(f"Frequently failed, should be waiting more then 3600s, break down!!!")
|
152 |
+
break
|
153 |
+
if waiting > 0:
|
154 |
+
time.sleep(waiting)
|
155 |
+
|
156 |
+
print(f'Total encoding sentences={len(sentences)}, embeddings={len(embs)}')
|
157 |
+
return embs
|
158 |
+
|
159 |
+
|
160 |
+
model_name = "text-embedding-3-large"
|
161 |
+
model_dim = 3072
|
162 |
+
model = OpenaiEmbModel(model_name, model_dim)
|
163 |
+
|
164 |
+
######
|
165 |
+
# test
|
166 |
+
#####
|
167 |
+
#embs = model.encode(['全国', '北京'])
|
168 |
+
#print(embs)
|
169 |
+
#exit()
|
170 |
+
|
171 |
+
# languages
|
172 |
+
task_langs=["zh", "zh-CN"]
|
173 |
+
|
174 |
+
evaluation = MTEB(task_types=task_list, task_langs=task_langs)
|
175 |
+
evaluation.run(model, output_folder=f"results/zh/{model_name.split('/')[-1]}")
|