server.py 11 KB

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