server.py 11 KB

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