server.py 13 KB

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