server.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import re
  2. import time
  3. import glob
  4. from sys import exit
  5. import torch
  6. import argparse
  7. from pathlib import Path
  8. import gradio as gr
  9. import transformers
  10. from html_generator import *
  11. from transformers import AutoTokenizer, AutoModelForCausalLM
  12. import warnings
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  15. parser.add_argument('--notebook', action='store_true', help='Launch the webui in notebook mode, where the output is written to the same text box as the input.')
  16. parser.add_argument('--chat', action='store_true', help='Launch the webui in chat mode.')
  17. parser.add_argument('--cai-chat', action='store_true', help='Launch the webui in chat mode with a style similar to Character.AI\'s. If the file profile.png exists in the same folder as server.py, this image will be used as the bot\'s profile picture.')
  18. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  19. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  20. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  21. parser.add_argument('--no-listen', action='store_true', help='Make the webui unreachable from your local network.')
  22. args = parser.parse_args()
  23. loaded_preset = None
  24. available_models = sorted(set(map(lambda x : str(x.name).replace('.pt', ''), list(Path('models/').glob('*'))+list(Path('torch-dumps/').glob('*')))))
  25. available_models = [item for item in available_models if not item.endswith('.txt')]
  26. available_models = sorted(available_models, key=str.lower)
  27. available_presets = sorted(set(map(lambda x : str(x.name).split('.')[0], list(Path('presets').glob('*.txt')))))
  28. transformers.logging.set_verbosity_error()
  29. def load_model(model_name):
  30. print(f"Loading {model_name}...")
  31. t0 = time.time()
  32. # Default settings
  33. if not (args.cpu or args.auto_devices or args.load_in_8bit):
  34. if Path(f"torch-dumps/{model_name}.pt").exists():
  35. print("Loading in .pt format...")
  36. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  37. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  38. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  39. else:
  40. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  41. # Custom
  42. else:
  43. settings = ["low_cpu_mem_usage=True"]
  44. cuda = ""
  45. command = "AutoModelForCausalLM.from_pretrained"
  46. if args.cpu:
  47. settings.append("torch_dtype=torch.float32")
  48. else:
  49. if args.load_in_8bit:
  50. settings.append("device_map='auto'")
  51. settings.append("load_in_8bit=True")
  52. else:
  53. settings.append("torch_dtype=torch.float16")
  54. if args.auto_devices:
  55. settings.append("device_map='auto'")
  56. else:
  57. cuda = ".cuda()"
  58. settings = ', '.join(settings)
  59. command = f"{command}(Path(f'models/{model_name}'), {settings}){cuda}"
  60. model = eval(command)
  61. # Loading the tokenizer
  62. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  63. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  64. else:
  65. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  66. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  67. return model, tokenizer
  68. # Removes empty replies from gpt4chan outputs
  69. def fix_gpt4chan(s):
  70. for i in range(10):
  71. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  72. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  73. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  74. return s
  75. # Fix the LaTeX equations in GALACTICA
  76. def fix_galactica(s):
  77. s = s.replace(r'\[', r'$')
  78. s = s.replace(r'\]', r'$')
  79. s = s.replace(r'\(', r'$')
  80. s = s.replace(r'\)', r'$')
  81. s = s.replace(r'$$', r'$')
  82. return s
  83. def generate_html(s):
  84. s = '\n'.join([f'<p style="margin-bottom: 20px">{line}</p>' for line in s.split('\n')])
  85. s = f'<div style="max-width: 600px; margin-left: auto; margin-right: auto; background-color:#eef2ff; color:#0b0f19; padding:3em; font-size:1.2em;">{s}</div>'
  86. return s
  87. def generate_reply(question, tokens, inference_settings, selected_model, eos_token=None):
  88. global model, tokenizer, model_name, loaded_preset, preset
  89. if selected_model != model_name:
  90. model_name = selected_model
  91. model = None
  92. tokenizer = None
  93. if not args.cpu:
  94. torch.cuda.empty_cache()
  95. model, tokenizer = load_model(model_name)
  96. if inference_settings != loaded_preset:
  97. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  98. preset = infile.read()
  99. loaded_preset = inference_settings
  100. if not args.cpu:
  101. torch.cuda.empty_cache()
  102. input_ids = tokenizer.encode(str(question), return_tensors='pt').cuda()
  103. cuda = ".cuda()"
  104. else:
  105. input_ids = tokenizer.encode(str(question), return_tensors='pt')
  106. cuda = ""
  107. if eos_token is None:
  108. output = eval(f"model.generate(input_ids, {preset}){cuda}")
  109. else:
  110. n = tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  111. output = eval(f"model.generate(input_ids, eos_token_id={n}, {preset}){cuda}")
  112. reply = tokenizer.decode(output[0], skip_special_tokens=True)
  113. reply = reply.replace(r'<|endoftext|>', '')
  114. if model_name.lower().startswith('galactica'):
  115. reply = fix_galactica(reply)
  116. return reply, reply, generate_html(reply)
  117. elif model_name.lower().startswith('gpt4chan'):
  118. reply = fix_gpt4chan(reply)
  119. return reply, 'Only applicable for galactica models.', generate_4chan_html(reply)
  120. else:
  121. return reply, 'Only applicable for galactica models.', generate_html(reply)
  122. # Choosing the default model
  123. if args.model is not None:
  124. model_name = args.model
  125. else:
  126. if len(available_models) == 0:
  127. print("No models are available! Please download at least one.")
  128. exit(0)
  129. elif len(available_models) == 1:
  130. i = 0
  131. else:
  132. print("The following models are available:\n")
  133. for i,model in enumerate(available_models):
  134. print(f"{i+1}. {model}")
  135. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  136. i = int(input())-1
  137. print()
  138. model_name = available_models[i]
  139. model, tokenizer = load_model(model_name)
  140. # UI settings
  141. if model_name.lower().startswith('gpt4chan'):
  142. default_text = "-----\n--- 865467536\nInput text\n--- 865467537\n"
  143. else:
  144. default_text = "Common sense questions and answers\n\nQuestion: \nFactual answer:"
  145. description = f"""
  146. # Text generation lab
  147. Generate text using Large Language Models.
  148. """
  149. css=".my-4 {margin-top: 0} .py-6 {padding-top: 2.5rem}"
  150. if args.notebook:
  151. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  152. gr.Markdown(description)
  153. with gr.Tab('Raw'):
  154. textbox = gr.Textbox(value=default_text, lines=23)
  155. with gr.Tab('Markdown'):
  156. markdown = gr.Markdown()
  157. with gr.Tab('HTML'):
  158. html = gr.HTML()
  159. btn = gr.Button("Generate")
  160. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_new_tokens', value=200)
  161. with gr.Row():
  162. with gr.Column():
  163. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  164. with gr.Column():
  165. preset_menu = gr.Dropdown(choices=available_presets, value="NovelAI-Sphinx Moth", label='Settings preset')
  166. btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=True, api_name="textgen")
  167. textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=True)
  168. elif args.chat or args.cai_chat:
  169. history = []
  170. # This gets the new line characters right.
  171. def chat_response_cleaner(text):
  172. text = text.replace('\n', '\n\n')
  173. text = re.sub(r"\n{3,}", "\n\n", text)
  174. text = text.strip()
  175. return text
  176. def chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check):
  177. text = chat_response_cleaner(text)
  178. question = context+'\n\n'
  179. for i in range(len(history)):
  180. question += f"{name1}: {history[i][0][3:-5].strip()}\n"
  181. question += f"{name2}: {history[i][1][3:-5].strip()}\n"
  182. question += f"{name1}: {text}\n"
  183. question += f"{name2}:"
  184. if check:
  185. reply = generate_reply(question, tokens, inference_settings, selected_model, eos_token='\n')[0]
  186. reply = reply[len(question):].split('\n')[0].strip()
  187. else:
  188. reply = generate_reply(question, tokens, inference_settings, selected_model)[0]
  189. reply = reply[len(question):]
  190. idx = reply.find(f"\n{name1}:")
  191. if idx != -1:
  192. reply = reply[:idx]
  193. reply = chat_response_cleaner(reply)
  194. history.append((text, reply))
  195. return history
  196. def cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check):
  197. history = chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check)
  198. return generate_chat_html(history, name1, name2)
  199. def remove_last_message(name1, name2):
  200. history.pop()
  201. if args.cai_chat:
  202. return generate_chat_html(history, name1, name2)
  203. else:
  204. return history
  205. def clear():
  206. global history
  207. history = []
  208. def clear_html():
  209. return generate_chat_html([], "", "")
  210. if 'pygmalion' in model_name.lower():
  211. context_str = "This is a conversation between two people.\n<START>"
  212. name1_str = "You"
  213. name2_str = "Kawaii"
  214. else:
  215. context_str = "This is a conversation between two people."
  216. name1_str = "Person 1"
  217. name2_str = "Person 2"
  218. with gr.Blocks(css=css+".h-\[40vh\] {height: 50vh}", analytics_enabled=False) as interface:
  219. gr.Markdown(description)
  220. with gr.Row():
  221. with gr.Column():
  222. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_new_tokens', value=200)
  223. with gr.Row():
  224. with gr.Column():
  225. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  226. with gr.Column():
  227. preset_menu = gr.Dropdown(choices=available_presets, value="NovelAI-Sphinx Moth", label='Settings preset')
  228. name1 = gr.Textbox(value=name1_str, lines=1, label='Your name')
  229. name2 = gr.Textbox(value=name2_str, lines=1, label='Bot\'s name')
  230. context = gr.Textbox(value=context_str, lines=2, label='Context')
  231. with gr.Row():
  232. check = gr.Checkbox(value=True, label='Stop generating at new line character?')
  233. with gr.Column():
  234. if args.cai_chat:
  235. display1 = gr.HTML(value=generate_chat_html([], "", ""))
  236. else:
  237. display1 = gr.Chatbot()
  238. textbox = gr.Textbox(lines=2, label='Input')
  239. btn = gr.Button("Generate")
  240. with gr.Row():
  241. with gr.Column():
  242. btn3 = gr.Button("Remove last message")
  243. with gr.Column():
  244. btn2 = gr.Button("Clear history")
  245. if args.cai_chat:
  246. btn.click(cai_chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=True, api_name="textgen")
  247. textbox.submit(cai_chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=True)
  248. btn2.click(clear_html, [], display1, show_progress=False)
  249. else:
  250. btn.click(chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=True, api_name="textgen")
  251. textbox.submit(chatbot_wrapper, [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check], display1, show_progress=True)
  252. btn2.click(lambda x: "", display1, display1)
  253. btn2.click(clear)
  254. btn3.click(remove_last_message, [name1, name2], display1, show_progress=False)
  255. btn.click(lambda x: "", textbox, textbox, show_progress=False)
  256. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  257. else:
  258. def continue_wrapper(question, tokens, inference_settings, selected_model):
  259. a, b, c = generate_reply(question, tokens, inference_settings, selected_model)
  260. return a, a, b, c
  261. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  262. gr.Markdown(description)
  263. with gr.Row():
  264. with gr.Column():
  265. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  266. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_new_tokens', value=200)
  267. preset_menu = gr.Dropdown(choices=available_presets, value="NovelAI-Sphinx Moth", label='Settings preset')
  268. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  269. btn = gr.Button("Generate")
  270. cont = gr.Button("Continue")
  271. with gr.Column():
  272. with gr.Tab('Raw'):
  273. output_textbox = gr.Textbox(lines=15, label='Output')
  274. with gr.Tab('Markdown'):
  275. markdown = gr.Markdown()
  276. with gr.Tab('HTML'):
  277. html = gr.HTML()
  278. btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=True, api_name="textgen")
  279. cont.click(continue_wrapper, [output_textbox, length_slider, preset_menu, model_menu], [output_textbox, textbox, markdown, html], show_progress=True)
  280. textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=True)
  281. if args.no_listen:
  282. interface.launch(share=False)
  283. else:
  284. interface.launch(share=False, server_name="0.0.0.0")