Spaces:
Runtime error
Runtime error
zetavg
commited on
Commit
•
91cd700
1
Parent(s):
da8868f
add llama_lora/utils/callbacks.py
Browse files
llama_lora/utils/callbacks.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Helpers to support streaming generate output.
|
3 |
+
Borrowed from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/callbacks.py
|
4 |
+
"""
|
5 |
+
|
6 |
+
import gc
|
7 |
+
import traceback
|
8 |
+
from queue import Queue
|
9 |
+
from threading import Thread
|
10 |
+
|
11 |
+
import torch
|
12 |
+
import transformers
|
13 |
+
|
14 |
+
|
15 |
+
class Stream(transformers.StoppingCriteria):
|
16 |
+
def __init__(self, callback_func=None):
|
17 |
+
self.callback_func = callback_func
|
18 |
+
|
19 |
+
def __call__(self, input_ids, scores) -> bool:
|
20 |
+
if self.callback_func is not None:
|
21 |
+
self.callback_func(input_ids[0])
|
22 |
+
return False
|
23 |
+
|
24 |
+
|
25 |
+
class Iteratorize:
|
26 |
+
|
27 |
+
"""
|
28 |
+
Transforms a function that takes a callback
|
29 |
+
into a lazy iterator (generator).
|
30 |
+
"""
|
31 |
+
|
32 |
+
def __init__(self, func, kwargs={}, callback=None):
|
33 |
+
self.mfunc = func
|
34 |
+
self.c_callback = callback
|
35 |
+
self.q = Queue()
|
36 |
+
self.sentinel = object()
|
37 |
+
self.kwargs = kwargs
|
38 |
+
self.stop_now = False
|
39 |
+
|
40 |
+
def _callback(val):
|
41 |
+
if self.stop_now:
|
42 |
+
raise ValueError
|
43 |
+
self.q.put(val)
|
44 |
+
|
45 |
+
def gentask():
|
46 |
+
try:
|
47 |
+
ret = self.mfunc(callback=_callback, **self.kwargs)
|
48 |
+
except ValueError:
|
49 |
+
pass
|
50 |
+
except:
|
51 |
+
traceback.print_exc()
|
52 |
+
pass
|
53 |
+
|
54 |
+
self.q.put(self.sentinel)
|
55 |
+
if self.c_callback:
|
56 |
+
self.c_callback(ret)
|
57 |
+
|
58 |
+
self.thread = Thread(target=gentask)
|
59 |
+
self.thread.start()
|
60 |
+
|
61 |
+
def __iter__(self):
|
62 |
+
return self
|
63 |
+
|
64 |
+
def __next__(self):
|
65 |
+
obj = self.q.get(True, None)
|
66 |
+
if obj is self.sentinel:
|
67 |
+
raise StopIteration
|
68 |
+
else:
|
69 |
+
return obj
|
70 |
+
|
71 |
+
def __enter__(self):
|
72 |
+
return self
|
73 |
+
|
74 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
75 |
+
self.stop_now = True
|