Repository navigation
Expand file tree
/
Copy pathdata_manager.py
More file actions
298 lines (244 loc) · 9.36 KB
/
Copy pathdata_manager.py
File metadata and controls
298 lines (244 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# -*- coding: utf-8 -*-
import logging
import time
import requests
import pickle
import numpy as np
import cachetools
from abc import abstractmethod, ABCMeta
from typing import List, Any, Optional, Union
from modelcache_mm.manager.scalar_data.base import (
CacheStorage,
CacheData,
DataType,
Answer,
Question
)
from modelcache_mm.utils.error import CacheError, ParamError
from modelcache_mm.manager.vector_data.base import VectorBase, VectorData
from modelcache_mm.manager.object_data.base import ObjectBase
from modelcache_mm.utils.log import modelcache_log
class DataManager(metaclass=ABCMeta):
"""DataManager manage the cache data, including save and search"""
@abstractmethod
def save(self, text, image_url, image_id, answer, embedding, **kwargs):
pass
@abstractmethod
def save_query_resp(self, query_resp_dict, **kwargs):
pass
@abstractmethod
def import_data(
self, texts: List[Any], image_urls: List[Any], image_ids: List[Any], answers: List[Answer],
embeddings: List[Any], model: Any, mm_type: Any
):
pass
@abstractmethod
def get_scalar_data(self, res_data, **kwargs) -> CacheData:
pass
@abstractmethod
def update_hit_count(self, primary_id, **kwargs):
pass
def hit_cache_callback(self, res_data, **kwargs):
pass
@abstractmethod
def search(self, embedding_data, **kwargs):
pass
@abstractmethod
def delete(self, id_list, **kwargs):
pass
def truncate(self, model_name):
pass
def flush(self):
pass
@abstractmethod
def close(self):
pass
class MapDataManager(DataManager):
def __init__(self, data_path, max_size, get_data_container=None):
if get_data_container is None:
self.data = cachetools.LRUCache(max_size)
else:
self.data = get_data_container(max_size)
self.data_path = data_path
self.init()
def init(self):
try:
with open(self.data_path, "rb") as f:
self.data = pickle.load(f)
except FileNotFoundError:
return
except PermissionError:
raise CacheError( # pylint: disable=W0707
f"You don't have permission to access this file <{self.data_path}>."
)
def save(self, text, image_url, image_id, answer, embedding, **kwargs):
pass
def save_query_resp(self, query_resp_dict, **kwargs):
pass
def import_data(
self, texts: List[Any], image_urls: List[Any], image_ids: List[Any], answers: List[Answer],
embeddings: List[Any], model: Any, mm_type: Any
):
pass
def get_scalar_data(self, res_data, **kwargs) -> CacheData:
return CacheData(question=res_data[0], answers=res_data[1])
def update_hit_count(self, primary_id, **kwargs):
pass
def search(self, embedding_data, **kwargs):
try:
return [self.data[embedding_data]]
except KeyError:
return []
def delete(self, id_list, **kwargs):
pass
def truncate(self, model_name):
pass
def flush(self):
try:
with open(self.data_path, "wb") as f:
pickle.dump(self.data, f)
except PermissionError:
modelcache_log.error(
"You don't have permission to access this file %s.", self.data_path
)
def close(self):
self.flush()
def normalize(vec):
magnitude = np.linalg.norm(vec)
normalized_v = vec / magnitude
return normalized_v
class SSDataManager(DataManager):
def __init__(
self,
s: CacheStorage,
v: VectorBase,
o: Optional[ObjectBase],
max_size,
clean_size,
policy="LRU",
):
self.max_size = max_size
self.clean_size = clean_size
self.s = s
self.v = v
self.o = o
def save(self, text, image_url, image_id, answer, embedding, **kwargs):
model = kwargs.pop("model", None)
mm_type = kwargs.pop("mm_type", None)
self.import_data([text], [image_url], [image_id], [answer], [embedding], model, mm_type)
def save_query_resp(self, query_resp_dict, **kwargs):
self.s.insert_query_resp(query_resp_dict, **kwargs)
def _process_answer_data(self, answers: Union[Answer, List[Answer]]):
if isinstance(answers, Answer):
answers = [answers]
new_ans = []
for ans in answers:
if ans.answer_type != DataType.STR:
new_ans.append(Answer(self.o.put(ans.answer), ans.answer_type))
else:
new_ans.append(ans)
return new_ans
def _process_question_data(self, question: Union[str, Question]):
if isinstance(question, Question):
if question.deps is None:
return question
for dep in question.deps:
if dep.dep_type == DataType.IMAGE_URL:
dep.dep_type.data = self.o.put(requests.get(dep.data).content)
return question
return Question(question)
def import_data(
self, texts: List[Any], image_urls: List[Any], image_ids: List[Any], answers: List[Answer],
embeddings: List[Any], model: Any, mm_type: Any
):
if len(texts) != len(answers):
raise ParamError("Make sure that all parameters have the same length")
cache_datas = []
embeddings = [
normalize(text_embedding) for text_embedding in embeddings
]
for i, embedding in enumerate(embeddings):
if self.o is not None:
ans = self._process_answer_data(answers[i])
else:
ans = answers[i]
text = texts[i]
image_url = image_urls[i]
image_id = image_ids[i]
cache_datas.append([ans, text, image_url, image_id, model])
ids = self.s.batch_insert(cache_datas)
self.v.add(
[
VectorData(id=ids[i], data=embedding)
for i, embedding in enumerate(embeddings)
],
model,
mm_type
)
def get_scalar_data(self, res_data, **kwargs) -> Optional[CacheData]:
cache_data = self.s.get_data_by_id(res_data[1])
if cache_data is None:
return None
return cache_data
def update_hit_count(self, primary_id, **kwargs):
self.s.update_hit_count_by_id(primary_id)
def hit_cache_callback(self, res_data, **kwargs):
self.eviction_base.get(res_data[1])
def search(self, embedding_data, **kwargs):
model = kwargs.pop("model", None)
mm_type = kwargs.pop("mm_type", None)
embedding_data = normalize(embedding_data)
top_k = kwargs.get("top_k", -1)
try:
search_result = self.v.search(data=embedding_data, top_k=top_k, model=model, mm_type=mm_type)
except Exception as e:
try:
message = str(e)
if "no such index" in message:
logging.info('no such index except,creating...')
self.v.create(model, mm_type)
search_result = self.v.search(data=embedding_data, top_k=top_k, model=model, mm_type=mm_type)
except Exception as e:
raise e
return search_result
def delete(self, id_list, **kwargs):
model = kwargs.pop("model", None)
try:
v_delete_count = self.v.delete(ids=id_list, model=model)
except Exception as e:
return {'status': 'failed', 'milvus': 'delete milvus data failed, please check! e: {}'.format(e),
'mysql': 'unexecuted'}
try:
s_delete_count = self.s.mark_deleted(id_list)
except Exception as e:
return {'status': 'failed', 'milvus': 'success',
'mysql': 'delete mysql data failed, please check! e: {}'.format(e)}
return {'status': 'success', 'milvus': 'delete_count: '+str(v_delete_count),
'mysql': 'delete_count: '+str(s_delete_count)}
def create_index(self, model, type, **kwargs):
return self.v.create(model, type)
def truncate(self, model_name):
try:
resp = self.v.rebuild_idx(model_name)
except Exception as e:
return {'status': 'failed', 'VectorDB': 'truncate VectorDB failed, please check! e: {}'.format(str(e)),
'ScalarDB': 'unexecuted'}
if resp:
return {'status': 'failed', 'VectorDB': resp, 'ScalarDB': 'unexecuted'}
try:
delete_count = self.s.model_deleted(model_name)
except Exception as e:
# return 'truncate milvus data failed, please check!'
return {'status': 'failed', 'VectorDB': 'rebuild',
'ScalarDB': 'truncate scalardb data failed, please check! e: {}'.format(e)}
return {'status': 'success', 'VectorDB': 'rebuild', 'ScalarDB': 'delete_count: ' + str(delete_count)}
def flush(self):
self.s.flush()
self.v.flush()
def close(self):
self.s.close()
self.v.close()
# if __name__ == '__main__':
# from modelcache.manager import CacheBase, VectorBase, get_data_manager
# data_manager = get_data_manager(CacheBase('mysql'), VectorBase('milvus', dimension=128))
# data_manager.save('hello', 'hi', np.random.random((128,)).astype('float32'), model='gptcode_6b')