server.py 12 KB

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