forked from ViperX7/Alpaca-Turbo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alpaca_turbo.py
executable file
·429 lines (373 loc) · 15.4 KB
/
alpaca_turbo.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/bin/python3
"""
▄▄▄· ▄▄▌ ▄▄▄· ▄▄▄· ▄▄· ▄▄▄· ▄▄▄▄▄▄• ▄▌▄▄▄ ▄▄▄▄·
▐█ ▀█ ██• ▐█ ▄█▐█ ▀█ ▐█ ▌▪▐█ ▀█ •██ █▪██▌▀▄ █·▐█ ▀█▪▪
▄█▀▀█ ██▪ ██▀·▄█▀▀█ ██ ▄▄▄█▀▀█ ▐█.▪█▌▐█▌▐▀▀▄ ▐█▀▀█▄ ▄█▀▄
▐█ ▪▐▌▐█▌▐▌▐█▪·•▐█ ▪▐▌▐███▌▐█ ▪▐▌ ▐█▌·▐█▄█▌▐█•█▌██▄▪▐█▐█▌.▐▌
▀ ▀ .▀▀▀ .▀ ▀ ▀ ·▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ .▀ ▀·▀▀▀▀ ▀█▄▀▪
https;//github.comViperX7/Alpaca-Turbo
"""
import os
import platform
import sys
from helpers.dtype import Conversation, load_all_conversations
from helpers.interaction import Process
from rich import print as eprint
class Assistant:
def __init__(self):
self.DEBUG = "-d" in sys.argv
self.threads = 4
self.top_k = 200
self.top_p = 0.99
self.temp = 0.7
self.repeat_penalty = 1
self.batch_size = 256
self.seed = 888777
self.n_predict = 1000
self.repeat_last_n = 512
self.use_bos = True
self.antiprompt = "### Human:"
self.models_directory = "models"
# self.history_size = 1500
# self.pre_prompt = " Below are instructions to a smart bot named devil, provide response inteligently to instructions.\n\n"
# self.pre_prompt = " Below are instructions provide best possible response and take into account entire history.\n\n"
self.pre_prompt = " Below is an instruction that describes a task. Write a response that appropriately completes the request."
self.format = "### Instruction:\n\n{instruction}\n\n### Response:\n\n{response}"
# self.pre_prompt = "you are a highly intelligent chatbot named devil and you remember all conversation history."
self.enable_history = False
self.history: list[Conversation] = []
self.end_marker = b"RSTsr"
self.model_idx = 0
self.is_loaded = ""
self.current_state = "Initialised"
self.old_preprompt = None
self.is_first_request = True
def load_chat(self, id):
"""load chat"""
result = {"can't load generation going on"}
if self.current_state != "generating":
data = load_all_conversations()
print(data)
return data[id]
def remove_all_chat(self):
"""hello world"""
# specify the path of the folder
folder_path = "conversations"
# loop through all files in the folder
r_count = 0
for file_name in os.listdir(folder_path):
# join the folder path and file name
file_path = os.path.join(folder_path, file_name)
# check if the file exists
if os.path.isfile(file_path):
# delete the file
os.remove(file_path)
r_count += 1
print(f"{r_count} deleted successfully")
return f"{r_count} files removed"
def save_chat(self):
"""load chat"""
result = "can't save generation going on"
if self.current_state != "generating":
if self.history:
Conversation.save(self.history)
result = "success"
else:
result = "no conversation to save"
return result
def get_conv_logs(self):
"""conversation logs"""
data = load_all_conversations()
return data
def clear_chat(self):
"""clear current history context"""
result = "can't save generation going on"
if self.current_state != "generating":
self.history = []
result = "success"
self.is_first_request = True
self.use_bos = True
return result
def safe_kill(self):
"""kill the bot if not in use"""
if self.current_state == "generating":
return "Can't kill bot busy"
self.process.killx()
self.is_first_request = True
self.current_state = "Initialised"
if self.history:
Conversation.save(self.history)
self.history = []
self.is_loaded = ""
return "killed the bot"
def list_available_models(self, directory_path="models", extension="bin"):
"""Returns a list of file names with the given extension given dir"""
file_list = []
for file in os.listdir(directory_path):
if file.endswith(extension):
file_list.append(os.path.join(directory_path, file))
return file_list
@staticmethod
def get_bin_path():
system_name = platform.system()
if os.path.exists("/main"):
name = "/main"
elif system_name == "Linux":
name = "bin/main"
elif system_name == "Windows":
name = "bin/main.exe"
elif system_name == "Darwin":
name = "bin/mac"
else:
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXX CHAT BINARY MISSING XXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
# elif system_name == "Android":
# return "Android"
# else:
# exit()
return name
@property
def command(self):
command = [
Assistant.get_bin_path(),
# "--color",
"-i",
"--seed",
f"{self.seed}",
"-ins",
"-t",
f"{self.threads}",
"-b",
f"{self.batch_size}",
"--top_k",
f"{self.top_k}",
"--top_p",
f"{self.top_p}",
"--repeat_last_n",
f"{self.repeat_last_n}",
"--repeat_penalty",
f"{self.repeat_penalty}",
"--temp",
f"{self.temp}",
"--n_predict",
f"{self.n_predict}",
"-m",
f"{self.list_available_models(self.models_directory)[self.model_idx]}",
# "--interactive-start",
"--interactive-first",
]
return command
def load_model(self):
"""load binary in memory"""
if self.is_loaded:
return (
f"model already loaded {self.list_available_models(self.models_directory)[self.model_idx]}"
)
try:
self.process = Process(self.command, timeout=10000)
for _ in range(6):
_ = (
[print("ERRoR" * 20), exit(1)]
if "error" in self.process.readline().decode("utf-8").lower()
else None
)
is_loaded = False
for _ in range(100):
if is_loaded:
continue
ppt = self.process.read(1)
is_loaded = b"d" == ppt
for _ in range(12):
(self.process.readline())
self.process.recvuntil(self.end_marker)
self.current_state = "prompt"
self.is_loaded = self.list_available_models(self.models_directory)[self.model_idx]
except Exception as e:
print(e)
self.is_loaded = ""
return f"Failed loading {self.list_available_models(self.models_directory)[self.model_idx]}"
return f"loaded successfully {self.list_available_models(self.models_directory)[self.model_idx]}"
def unload_model(self):
if self.is_loaded:
self.safe_kill()
self.is_loaded = False
def action(self, command):
"""returns whether a request can be colmpleted or not"""
if command == "generate":
is_possible = self.current_state == "prompt"
if command == "stop":
is_possible = self.current_state == "generating"
return is_possible
def stop_generation(self):
"""Interrupts generation"""
if self.current_state == "generating":
self.current_state = "stoping_generation"
# self.process.send("\003")
self.process.interrupt()
self.current_state = "prompt"
return "Stopped"
return f"failed to stop current status {self.current_state}"
def chatbot(self, prompt: Conversation):
"""Adds history support"""
self.history.append(prompt)
# build history chahe
final_prompt_2_send = []
data2use = self.history if self.enable_history else [self.history[-1]]
for convo in data2use:
for sequence in convo.get_prompt():
final_prompt_2_send.append(sequence)
final_prompt_2_send = "".join(final_prompt_2_send)
if prompt.preprompt:
final_prompt_2_send = [prompt.preprompt, final_prompt_2_send]
self.send_prompts(final_prompt_2_send)
for char in self.stream_generation():
self.history[-1].response += char
yield char
def send_prompts(self, txtblob):
"""send the prompts with bos token"""
eprint(txtblob)
txtblob = txtblob if isinstance(txtblob, list) else [txtblob]
_ = eprint(txtblob) if self.DEBUG else None
if self.action("generate"):
bos = len(txtblob)
self.process.recvuntil("n_inps> ")
self.process.sendline(str(bos))
self.process.recvuntil("n_threads> ")
self.process.sendline(str(self.threads))
self.process.recvuntil("top_k> ")
self.process.sendline(str(self.top_k))
self.process.recvuntil("top_p> ")
self.process.sendline(str(self.top_p))
self.process.recvuntil("temperature> ")
self.process.sendline(str(self.temp))
self.process.recvuntil("repeat_penalty> ")
self.process.sendline(str(self.repeat_penalty))
self.process.recvuntil("n_batch> ")
self.process.sendline(str(self.batch_size))
self.process.recvuntil("antiprompt> ")
self.process.sendline(str(self.antiprompt))
for txt in txtblob:
lines = txt.split("\n")
lines[-1] += "@end@" if self.use_bos else "@done@"
self.use_bos = False
for line in lines:
self.process.recvuntil(") : ")
self.process.sendline(line)
# print(self.process.readline())
self.current_state = "generating"
else:
print("CRITICAL")
def stream_generation(self):
"""returns a generator that returns the generation"""
buffer = b""
marker_detected = b""
antiprompt_detected = b""
char_old = b""
while self.current_state == "generating":
char = self.process.read(1)
buffer += char # update the buffer
# Detect end of text if detected try to confirm else reset
if (
char == self.end_marker.decode()[0].encode("utf-8")
or len(marker_detected) > 0
):
marker_detected += char
char_old += char
# print("==========")
# print(marker_detected)
# print(self.end_marker[:len(marker_detected)])
if marker_detected in self.end_marker[: len(marker_detected)]:
# print("cont")
continue
marker_detected = b""
elif (
char == self.antiprompt[0].encode("utf-8")
or len(antiprompt_detected) > 0
):
antiprompt_detected += char
char_old += char
# print("==========")
# print(antiprompt_detected)
# print(self.end_antiprompt[:len(antiprompt_detected)])
if antiprompt_detected in self.antiprompt[
: len(antiprompt_detected)
].encode("utf-8"):
# print("cont")
continue
antiprompt_detected = b""
if self.antiprompt.encode("utf-8") in buffer:
buffer = buffer.replace(self.antiprompt.encode("utf-8"), b"")
buffer = buffer[:-1] if buffer[-1] == 10 else buffer
char_old = char_old.replace(self.antiprompt.encode("utf-8"), b"")
char_old = char_old[:-1] if char_old[-1] == 10 else char_old
if self.end_marker in buffer:
buffer = buffer.replace(self.end_marker, b"")
char_old += char
char_old = char_old.replace(self.end_marker, b"")
self.current_state = "prompt"
try:
res = char_old.decode("utf-8")
except UnicodeDecodeError:
res = f">{str(char_old)}<"
yield res
# print(f"\nStream Ended {buffer}")
break
try:
# Load the full character cache
char = char_old + char
# print single printable chars
if len(char) == 1 and char[0] <= 0x7E and char[0] >= 0x21:
char = char.decode("utf-8")
char_old = b""
elif len(char) >= 4:
char = char.decode("utf-8")
char_old = b""
else:
char_old = char
continue
except UnicodeDecodeError:
char_old = char
continue
# print(char, end="")
yield char
# return buffer
def send_conv(self, preprompt, fmt, prompt):
"""function to simplify interface"""
if self.old_preprompt is None:
self.old_preprompt = preprompt
elif self.old_preprompt is not None and self.old_preprompt != preprompt:
self.old_preprompt = preprompt
elif self.old_preprompt == preprompt:
preprompt = None
preprompt = preprompt if preprompt is not None else None
preprompt = self.pre_prompt if self.is_first_request else preprompt
self.is_first_request = False
fmt = self.format if fmt is None else fmt
conv = Conversation(preprompt, fmt, prompt)
resp = self.chatbot(conv)
return resp
@staticmethod
def repl():
"""Repl for my chat bot"""
assistant = Assistant()
assistant.load_model()
assistant.enable_history = False
fmt = assistant.format
# assistant.pre_prompt = ""
preprompt = assistant.pre_prompt
while True:
# print("=====")
prompt = input(">>>>>> ")
preprompt = ""
resp = assistant.send_conv(preprompt, fmt, prompt)
for char in resp:
print(char, end="")
print()
_ = Assistant.repl() if __name__ == "__main__" else None