-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathdata_manager.py
413 lines (349 loc) · 13.1 KB
/
data_manager.py
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import pickle
from abc import abstractmethod, ABCMeta
from typing import List, Any, Optional, Union
import cachetools
import numpy as np
import requests
from gptcache.manager.eviction import EvictionBase
from gptcache.manager.eviction.distributed_cache import NoOpEviction
from gptcache.manager.eviction_manager import EvictionManager
from gptcache.manager.object_data.base import ObjectBase
from gptcache.manager.scalar_data.base import (
CacheStorage,
CacheData,
DataType,
Answer,
Question,
)
from gptcache.manager.vector_data.base import VectorBase, VectorData
from gptcache.utils.error import CacheError, ParamError
from gptcache.utils.log import gptcache_log
class DataManager(metaclass=ABCMeta):
"""DataManager manage the cache data, including save and search"""
@abstractmethod
def save(self, question, answer, embedding_data, **kwargs):
pass
@abstractmethod
def import_data(
self,
questions: List[Any],
answers: List[Any],
embedding_datas: List[Any],
session_ids: List[Optional[str]],
):
pass
@abstractmethod
def get_scalar_data(self, res_data, **kwargs) -> CacheData:
pass
def hit_cache_callback(self, res_data, **kwargs):
pass
@abstractmethod
def search(self, embedding_data, **kwargs):
"""search the data in the cache store accrodding to the embedding data
:return: a list of search result, [[score, id], [score, id], ...]
"""
pass
def flush(self):
pass
@abstractmethod
def add_session(self, res_data, session_id, pre_embedding_data):
pass
@abstractmethod
def list_sessions(self, session_id, key):
pass
@abstractmethod
def delete_session(self, session_id):
pass
def report_cache(
self,
user_question,
cache_question,
cache_question_id,
cache_answer,
similarity_value,
cache_delta_time,
):
pass
@abstractmethod
def close(self):
pass
class MapDataManager(DataManager):
"""MapDataManager, store all data in a map data structure.
:param data_path: the path to save the map data, defaults to 'data_map.txt'.
:type data_path: str
:param max_size: the max size for the cache, defaults to 1000.
:type max_size: int
:param get_data_container: a Callable to get the data container, defaults to None.
:type get_data_container: Callable
Example:
.. code-block:: python
from gptcache.manager import get_data_manager
data_manager = get_data_manager("data_map.txt", 1000)
"""
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, question, answer, embedding_data, **kwargs):
if isinstance(question, Question):
question = question.content
session = kwargs.get("session", None)
session_id = {session.name} if session else set()
self.data[embedding_data] = (question, answer, embedding_data, session_id)
def import_data(
self,
questions: List[Any],
answers: List[Any],
embedding_datas: List[Any],
session_ids: List[Optional[str]],
):
if (
len(questions) != len(answers)
or len(questions) != len(embedding_datas)
or len(questions) != len(session_ids)
):
raise ParamError("Make sure that all parameters have the same length")
for i, embedding_data in enumerate(embedding_datas):
self.data[embedding_data] = (
questions[i],
answers[i],
embedding_datas[i],
{session_ids[i]} if session_ids[i] else set(),
)
def get_scalar_data(self, res_data, **kwargs) -> CacheData:
session = kwargs.get("session", None)
if session:
answer = (
res_data[1].answer if isinstance(res_data[1], Answer) else res_data[1]
)
if not session.check_hit_func(
session.name, list(res_data[3]), [res_data[0]], answer
):
return None
return CacheData(question=res_data[0], answers=res_data[1])
def search(self, embedding_data, **kwargs):
try:
return [self.data[embedding_data]]
except KeyError:
return []
def flush(self):
try:
with open(self.data_path, "wb") as f:
pickle.dump(self.data, f)
except PermissionError:
gptcache_log.error(
"You don't have permission to access this file %s.", self.data_path
)
def add_session(self, res_data, session_id, pre_embedding_data):
res_data[3].add(session_id)
def list_sessions(self, session_id=None, key=None):
session_ids = set()
for k in self.data:
if session_id and session_id in self.data[k][3]:
session_ids.add(k)
elif len(self.data[k][3]) > 0:
session_ids.update(self.data[k][3])
return list(session_ids)
def delete_session(self, session_id):
keys = self.list_sessions(session_id=session_id)
for k in keys:
self.data[k][3].remove(session_id)
if len(self.data[k][3]) == 0:
del self.data[k]
def close(self):
self.flush()
def normalize(vec):
magnitude = np.linalg.norm(vec)
normalized_v = vec / magnitude
return normalized_v
class SSDataManager(DataManager):
"""Generate SSDataManage to manager the data.
:param s: CacheStorage to manager the scalar data, it can be generated with :meth:`gptcache.manager.CacheBase`.
:type s: CacheStorage
:param v: VectorBase to manager the vector data, it can be generated with :meth:`gptcache.manager.VectorBase`.
:type v: VectorBase
:param o: ObjectBase to manager the object data, it can be generated with :meth:`gptcache.manager.ObjectBase`.
:type o: ObjectBase
:param e: EvictionBase to manager the eviction data, it can be generated with :meth:`gptcache.manager.EvictionBase`.
:type e: EvictionBase
"""
def __init__(
self,
s: CacheStorage,
v: VectorBase,
o: Optional[ObjectBase],
e: Optional[EvictionBase],
max_size,
clean_size,
policy="LRU"
):
self.s = s
self.v = v
self.o = o
self.eviction_manager = EvictionManager(self.s, self.v)
if e is None:
e = EvictionBase(name="memory",
maxsize=max_size,
clean_size=clean_size,
policy=policy,
on_evict=self._clear)
self.eviction_base = e
if not isinstance(self.eviction_base, NoOpEviction):
# if eviction manager is no op redis, we don't need to put data into eviction base
self.eviction_base.put(self.s.get_ids(deleted=False))
def _clear(self, marked_keys):
self.eviction_manager.soft_evict(marked_keys)
if self.eviction_manager.check_evict():
self.eviction_manager.delete()
def save(self, question, answer, embedding_data, **kwargs):
"""Save the data and vectors to cache and vector storage.
:param question: question data.
:type question: str
:param answer: answer data.
:type answer: str, Answer or (Any, DataType)
:param embedding_data: vector data.
:type embedding_data: np.ndarray
Example:
.. code-block:: python
import numpy as np
from gptcache.manager import get_data_manager, CacheBase, VectorBase
data_manager = get_data_manager(CacheBase('sqlite'), VectorBase('faiss', dimension=128))
data_manager.save('hello', 'hi', np.random.random((128, )).astype('float32'))
"""
session = kwargs.get("session", None)
session_id = session.name if session else None
self.import_data([question], [answer], [embedding_data], [session_id])
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,
questions: List[Any],
answers: List[Answer],
embedding_datas: List[Any],
session_ids: List[Optional[str]],
):
if (
len(questions) != len(answers)
or len(questions) != len(embedding_datas)
or len(questions) != len(session_ids)
):
raise ParamError("Make sure that all parameters have the same length")
cache_datas = []
embedding_datas = [
normalize(embedding_data) for embedding_data in embedding_datas
]
for i, embedding_data in enumerate(embedding_datas):
if self.o is not None and not isinstance(answers[i], str):
ans = self._process_answer_data(answers[i])
else:
ans = answers[i]
cache_datas.append(
CacheData(
question=self._process_question_data(questions[i]),
answers=ans,
embedding_data=embedding_data.astype("float32"),
session_id=session_ids[i],
)
)
ids = self.s.batch_insert(cache_datas)
self.v.mul_add(
[
VectorData(id=ids[i], data=embedding_data)
for i, embedding_data in enumerate(embedding_datas)
]
)
self.eviction_base.put(ids)
def get_scalar_data(self, res_data, **kwargs) -> Optional[CacheData]:
session = kwargs.get("session", None)
cache_data = self.s.get_data_by_id(res_data[1])
if cache_data is None:
return None
if session:
cache_answer = (
cache_data.answers[0].answer
if isinstance(cache_data.answers[0], Answer)
else cache_data.answers[0]
)
res_list = self.list_sessions(key=res_data[1])
cache_session_ids, cache_questions = [r.session_id for r in res_list], [
r.session_question for r in res_list
]
if not session.check_hit_func(
session.name, cache_session_ids, cache_questions, cache_answer
):
return None
for ans in cache_data.answers:
if ans.answer_type != DataType.STR:
ans.answer = self.o.get(ans.answer)
return cache_data
def hit_cache_callback(self, res_data, **kwargs):
self.eviction_base.get(res_data[1])
def search(self, embedding_data, **kwargs):
embedding_data = normalize(embedding_data)
top_k = kwargs.get("top_k", -1)
return self.v.search(data=embedding_data, top_k=top_k)
def flush(self):
self.s.flush()
self.v.flush()
def add_session(self, res_data, session_id, pre_embedding_data):
self.s.add_session(res_data[1], session_id, pre_embedding_data)
def list_sessions(self, session_id=None, key=None):
res = self.s.list_sessions(session_id, key)
if key:
return res
if session_id:
return list(r.id for r in res)
return list(set(r.session_id for r in res))
def delete_session(self, session_id):
keys = self.list_sessions(session_id=session_id)
self.s.delete_session(keys)
def report_cache(
self,
user_question,
cache_question,
cache_question_id,
cache_answer,
similarity_value,
cache_delta_time,
):
self.s.report_cache(
user_question,
cache_question,
cache_question_id,
cache_answer,
similarity_value,
cache_delta_time,
)
def close(self):
self.s.close()
self.v.close()