server.py 10 KB

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