server.py 11 KB

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