server.py 11 KB

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