server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import re
  2. import time
  3. import glob
  4. from sys import exit
  5. import torch
  6. import argparse
  7. import json
  8. from pathlib import Path
  9. import gradio as gr
  10. import transformers
  11. from html_generator import *
  12. from transformers import AutoTokenizer, AutoModelForCausalLM
  13. import warnings
  14. import gc
  15. from tqdm import tqdm
  16. transformers.logging.set_verbosity_error()
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  19. parser.add_argument('--notebook', action='store_true', help='Launch the web UI in notebook mode, where the output is written to the same text box as the input.')
  20. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  21. parser.add_argument('--cai-chat', action='store_true', help='Launch the web UI in chat mode with a style similar to Character.AI\'s. If the file profile.png or profile.jpg exists in the same folder as server.py, this image will be used as the bot\'s profile picture.')
  22. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  23. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  24. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  25. parser.add_argument('--disk', action='store_true', help='If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.')
  26. parser.add_argument('--max-gpu-memory', type=int, help='Maximum memory in GiB to allocate to the GPU when loading the model. This is useful if you get out of memory errors while trying to generate text. Must be an integer number.')
  27. parser.add_argument('--no-listen', action='store_true', help='Make the web UI unreachable from your local network.')
  28. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This slightly improves the text generation performance.')
  29. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  30. args = parser.parse_args()
  31. loaded_preset = None
  32. available_models = sorted(set([item.replace('.pt', '') for item in map(lambda x : str(x.name), list(Path('models/').glob('*'))+list(Path('torch-dumps/').glob('*'))) if not item.endswith('.txt')]), key=str.lower)
  33. available_presets = sorted(set(map(lambda x : str(x.name).split('.')[0], Path('presets').glob('*.txt'))), key=str.lower)
  34. settings = {
  35. 'max_new_tokens': 200,
  36. 'max_new_tokens_min': 1,
  37. 'max_new_tokens_max': 2000,
  38. 'preset': 'NovelAI-Sphinx Moth',
  39. 'name1': 'Person 1',
  40. 'name2': 'Person 2',
  41. 'name1_pygmalion': 'You',
  42. 'name2_pygmalion': 'Kawaii',
  43. 'context': 'This is a conversation between two people.',
  44. 'context_pygmalion': 'This is a conversation between two people.\n<START>',
  45. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  46. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  47. 'stop_at_newline': True,
  48. }
  49. if args.settings is not None and Path(args.settings).exists():
  50. with open(Path(args.settings), 'r') as f:
  51. new_settings = json.load(f)
  52. for item in new_settings:
  53. if item in settings:
  54. settings[item] = new_settings[item]
  55. def load_model(model_name):
  56. print(f"Loading {model_name}...")
  57. t0 = time.time()
  58. # Default settings
  59. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.max_gpu_memory is not None):
  60. if Path(f"torch-dumps/{model_name}.pt").exists():
  61. print("Loading in .pt format...")
  62. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  63. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  64. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  65. else:
  66. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  67. # Custom
  68. else:
  69. settings = ["low_cpu_mem_usage=True"]
  70. command = "AutoModelForCausalLM.from_pretrained"
  71. if args.cpu:
  72. settings.append("torch_dtype=torch.float32")
  73. else:
  74. settings.append("device_map='auto'")
  75. if args.max_gpu_memory is not None:
  76. settings.append(f"max_memory={{0: '{args.max_gpu_memory}GiB', 'cpu': '99GiB'}}")
  77. if args.disk:
  78. settings.append("offload_folder='cache'")
  79. if args.load_in_8bit:
  80. settings.append("load_in_8bit=True")
  81. else:
  82. settings.append("torch_dtype=torch.float16")
  83. settings = ', '.join(set(settings))
  84. command = f"{command}(Path(f'models/{model_name}'), {settings})"
  85. model = eval(command)
  86. # Loading the tokenizer
  87. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  88. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  89. else:
  90. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  91. tokenizer.truncation_side = 'left'
  92. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  93. return model, tokenizer
  94. # Removes empty replies from gpt4chan outputs
  95. def fix_gpt4chan(s):
  96. for i in range(10):
  97. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  98. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  99. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  100. return s
  101. # Fix the LaTeX equations in galactica
  102. def fix_galactica(s):
  103. s = s.replace(r'\[', r'$')
  104. s = s.replace(r'\]', r'$')
  105. s = s.replace(r'\(', r'$')
  106. s = s.replace(r'\)', r'$')
  107. s = s.replace(r'$$', r'$')
  108. return s
  109. def encode(prompt, tokens):
  110. if not args.cpu:
  111. torch.cuda.empty_cache()
  112. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens).cuda()
  113. else:
  114. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens)
  115. return input_ids
  116. def decode(output_ids):
  117. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  118. reply = reply.replace(r'<|endoftext|>', '')
  119. return reply
  120. def formatted_outputs(reply, model_name):
  121. if model_name.lower().startswith('galactica'):
  122. reply = fix_galactica(reply)
  123. return reply, reply, generate_basic_html(reply)
  124. elif model_name.lower().startswith('gpt4chan'):
  125. reply = fix_gpt4chan(reply)
  126. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  127. else:
  128. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  129. def generate_reply(question, tokens, inference_settings, selected_model, eos_token=None):
  130. global model, tokenizer, model_name, loaded_preset, preset
  131. if selected_model != model_name:
  132. model_name = selected_model
  133. model = None
  134. tokenizer = None
  135. if not args.cpu:
  136. gc.collect()
  137. torch.cuda.empty_cache()
  138. model, tokenizer = load_model(model_name)
  139. if inference_settings != loaded_preset:
  140. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  141. preset = infile.read()
  142. loaded_preset = inference_settings
  143. cuda = "" if args.cpu else ".cuda()"
  144. n = None if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  145. # Generate the entire reply at once
  146. if args.no_stream:
  147. input_ids = encode(question, tokens)
  148. output = eval(f"model.generate(input_ids, eos_token_id={n}, {preset}){cuda}")
  149. reply = decode(output[0])
  150. yield formatted_outputs(reply, model_name)
  151. # Generate the reply 1 token at a time
  152. else:
  153. yield formatted_outputs(question, model_name)
  154. input_ids = encode(question, 1)
  155. preset = preset.replace('max_new_tokens=tokens', 'max_new_tokens=1')
  156. for i in tqdm(range(tokens)):
  157. output = eval(f"model.generate(input_ids, {preset}){cuda}")
  158. reply = decode(output[0])
  159. if eos_token is not None and reply[-1] == eos_token:
  160. break
  161. yield formatted_outputs(reply, model_name)
  162. input_ids = output
  163. # Choosing the default model
  164. if args.model is not None:
  165. model_name = args.model
  166. else:
  167. if len(available_models) == 0:
  168. print("No models are available! Please download at least one.")
  169. exit(0)
  170. elif len(available_models) == 1:
  171. i = 0
  172. else:
  173. print("The following models are available:\n")
  174. for i,model in enumerate(available_models):
  175. print(f"{i+1}. {model}")
  176. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  177. i = int(input())-1
  178. print()
  179. model_name = available_models[i]
  180. model, tokenizer = load_model(model_name)
  181. # UI settings
  182. if model_name.lower().startswith('gpt4chan'):
  183. default_text = settings['prompt_gpt4chan']
  184. else:
  185. default_text = settings['prompt']
  186. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  187. css = ".my-4 {margin-top: 0} .py-6 {padding-top: 2.5rem}"
  188. if args.chat or args.cai_chat:
  189. history = []
  190. # This gets the new line characters right.
  191. def clean_chat_message(text):
  192. text = text.replace('\n', '\n\n')
  193. text = re.sub(r"\n{3,}", "\n\n", text)
  194. text = text.strip()
  195. return text
  196. def generate_chat_prompt(text, tokens, name1, name2, context):
  197. text = clean_chat_message(text)
  198. rows = [f"{context}\n\n"]
  199. i = len(history)-1
  200. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < 2048-tokens:
  201. rows.insert(1, f"{name2}: {history[i][1].strip()}\n")
  202. rows.insert(1, f"{name1}: {history[i][0].strip()}\n")
  203. i -= 1
  204. rows.append(f"{name1}: {text}\n")
  205. rows.append(f"{name2}:")
  206. while len(rows) > 3 and len(encode(''.join(rows), tokens)[0]) >= 2048-tokens:
  207. rows.pop(1)
  208. rows.pop(1)
  209. question = ''.join(rows)
  210. return question
  211. def chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check):
  212. question = generate_chat_prompt(text, tokens, name1, name2, context)
  213. history.append(['', ''])
  214. eos_token = '\n' if check else None
  215. for i in generate_reply(question, tokens, inference_settings, selected_model, eos_token=eos_token):
  216. reply = i[0]
  217. next_character_found = False
  218. if check:
  219. idx = reply.rfind(question[-1024:])
  220. reply = reply[idx+min(1024, len(question)):].split('\n')[0].strip()
  221. else:
  222. idx = reply.rfind(question[-1024:])
  223. reply = reply[idx+min(1024, len(question)):]
  224. idx = reply.find(f"\n{name1}:")
  225. if idx != -1:
  226. reply = reply[:idx]
  227. next_character_found = True
  228. reply = clean_chat_message(reply)
  229. history[-1] = [text, reply]
  230. if next_character_found:
  231. break
  232. # Prevent the chat log from flashing if something like "\nYo" is generated just
  233. # before "\nYou:" is completed
  234. tmp = f"\n{name1}:"
  235. next_character_substring_found = False
  236. for j in range(1, len(tmp)):
  237. if reply[-j:] == tmp[:j]:
  238. next_character_substring_found = True
  239. if not next_character_substring_found:
  240. yield history
  241. yield history
  242. def cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check):
  243. for history in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check):
  244. yield generate_chat_html(history, name1, name2)
  245. def remove_last_message(name1, name2):
  246. history.pop()
  247. if args.cai_chat:
  248. return generate_chat_html(history, name1, name2)
  249. else:
  250. return history
  251. def clear():
  252. global history
  253. history = []
  254. def clear_html():
  255. return generate_chat_html([], "", "")
  256. def redraw_html(name1, name2):
  257. global history
  258. return generate_chat_html(history, name1, name2)
  259. def save_history():
  260. if not Path('logs').exists():
  261. Path('logs').mkdir()
  262. with open(Path('logs/conversation.json'), 'w') as f:
  263. f.write(json.dumps({'data': history}))
  264. return Path('logs/conversation.json')
  265. def load_history(file):
  266. global history
  267. history = json.loads(file.decode('utf-8'))['data']
  268. if 'pygmalion' in model_name.lower():
  269. context_str = settings['context_pygmalion']
  270. name1_str = settings['name1_pygmalion']
  271. name2_str = settings['name2_pygmalion']
  272. else:
  273. context_str = settings['context']
  274. name1_str = settings['name1']
  275. name2_str = settings['name2']
  276. with gr.Blocks(css=css+".h-\[40vh\] {height: 66.67vh} .gradio-container {max-width: 800px; margin-left: auto; margin-right: auto}", analytics_enabled=False) as interface:
  277. if args.cai_chat:
  278. display1 = gr.HTML(value=generate_chat_html([], "", ""))
  279. else:
  280. display1 = gr.Chatbot()
  281. textbox = gr.Textbox(lines=2, label='Input')
  282. btn = gr.Button("Generate")
  283. with gr.Row():
  284. btn2 = gr.Button("Clear history")
  285. stop = gr.Button("Stop")
  286. btn3 = gr.Button("Remove last message")
  287. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  288. with gr.Row():
  289. with gr.Column():
  290. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  291. with gr.Column():
  292. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  293. name1 = gr.Textbox(value=name1_str, lines=1, label='Your name')
  294. name2 = gr.Textbox(value=name2_str, lines=1, label='Bot\'s name')
  295. context = gr.Textbox(value=context_str, lines=2, label='Context')
  296. with gr.Row():
  297. check = gr.Checkbox(value=settings['stop_at_newline'], label='Stop generating at new line character?')
  298. with gr.Row():
  299. with gr.Column():
  300. gr.Markdown("Upload chat history")
  301. upload = gr.File(type='binary')
  302. with gr.Column():
  303. gr.Markdown("Download chat history")
  304. save_btn = gr.Button(value="Click me")
  305. download = gr.File()
  306. if args.cai_chat:
  307. gen_event = btn.click(cai_chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=args.no_stream, api_name="textgen")
  308. gen_event2 = textbox.submit(cai_chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=args.no_stream)
  309. btn2.click(clear_html, [], display1, show_progress=False)
  310. else:
  311. gen_event = btn.click(chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=args.no_stream, api_name="textgen")
  312. gen_event2 = textbox.submit(chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=args.no_stream)
  313. btn2.click(lambda x: "", display1, display1, show_progress=False)
  314. btn2.click(clear)
  315. btn3.click(remove_last_message, [name1, name2], display1, show_progress=False)
  316. btn.click(lambda x: "", textbox, textbox, show_progress=False)
  317. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  318. stop.click(None, None, None, cancels=[gen_event, gen_event2])
  319. save_btn.click(save_history, inputs=[], outputs=[download])
  320. upload.upload(load_history, [upload], [])
  321. upload.upload(redraw_html, [name1, name2], [display1])
  322. elif args.notebook:
  323. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  324. gr.Markdown(description)
  325. with gr.Tab('Raw'):
  326. textbox = gr.Textbox(value=default_text, lines=23)
  327. with gr.Tab('Markdown'):
  328. markdown = gr.Markdown()
  329. with gr.Tab('HTML'):
  330. html = gr.HTML()
  331. btn = gr.Button("Generate")
  332. stop = gr.Button("Stop")
  333. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  334. with gr.Row():
  335. with gr.Column():
  336. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  337. with gr.Column():
  338. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  339. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  340. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream)
  341. stop.click(None, None, None, cancels=[gen_event, gen_event2])
  342. else:
  343. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  344. gr.Markdown(description)
  345. with gr.Row():
  346. with gr.Column():
  347. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  348. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  349. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  350. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  351. btn = gr.Button("Generate")
  352. with gr.Row():
  353. with gr.Column():
  354. cont = gr.Button("Continue")
  355. with gr.Column():
  356. stop = gr.Button("Stop")
  357. with gr.Column():
  358. with gr.Tab('Raw'):
  359. output_textbox = gr.Textbox(lines=15, label='Output')
  360. with gr.Tab('Markdown'):
  361. markdown = gr.Markdown()
  362. with gr.Tab('HTML'):
  363. html = gr.HTML()
  364. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  365. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  366. cont_event = cont.click(generate_reply, [output_textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  367. stop.click(None, None, None, cancels=[gen_event, gen_event2, cont_event])
  368. interface.queue()
  369. if args.no_listen:
  370. interface.launch(share=False)
  371. else:
  372. interface.launch(share=False, server_name="0.0.0.0")