server.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. args = parser.parse_args()
  17. loaded_preset = None
  18. available_models = sorted(set(map(lambda x : str(x.name).replace('.pt', ''), list(Path('models/').glob('*'))+list(Path('torch-dumps/').glob('*')))))
  19. available_models = [item for item in available_models if not item.endswith('.txt')]
  20. available_presets = sorted(set(map(lambda x : str(x.name).split('.')[0], list(Path('presets').glob('*.txt')))))
  21. def load_model(model_name):
  22. print(f"Loading {model_name}...")
  23. t0 = time.time()
  24. # Loading the model
  25. if Path(f"torch-dumps/{model_name}.pt").exists():
  26. print("Loading in .pt format...")
  27. model = torch.load(Path(f"torch-dumps/{model_name}.pt")).cuda()
  28. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')):
  29. if any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  30. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  31. else:
  32. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  33. elif model_name in ['gpt-j-6B']:
  34. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  35. elif model_name in ['flan-t5', 't5-large']:
  36. model = T5ForConditionalGeneration.from_pretrained(Path(f"models/{model_name}")).cuda()
  37. else:
  38. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  39. # Loading the tokenizer
  40. if model_name.startswith('gpt4chan'):
  41. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  42. elif model_name in ['flan-t5']:
  43. tokenizer = T5Tokenizer.from_pretrained(Path(f"models/{model_name}/"))
  44. else:
  45. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  46. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  47. return model, tokenizer
  48. # Removes empty replies from gpt4chan outputs
  49. def fix_gpt4chan(s):
  50. for i in range(10):
  51. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  52. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  53. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  54. return s
  55. def fix_galactica(s):
  56. s = s.replace(r'\[', r'$')
  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. return s
  62. def generate_reply(question, temperature, max_length, inference_settings, selected_model):
  63. global model, tokenizer, model_name, loaded_preset, preset
  64. if selected_model != model_name:
  65. model_name = selected_model
  66. model = None
  67. tokenier = None
  68. torch.cuda.empty_cache()
  69. model, tokenizer = load_model(model_name)
  70. if inference_settings != loaded_preset:
  71. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  72. preset = infile.read()
  73. loaded_preset = inference_settings
  74. torch.cuda.empty_cache()
  75. input_text = question
  76. input_ids = tokenizer.encode(str(input_text), return_tensors='pt').cuda()
  77. output = eval(f"model.generate(input_ids, {preset}).cuda()")
  78. reply = tokenizer.decode(output[0], skip_special_tokens=True)
  79. if model_name.lower().startswith('galactica'):
  80. reply = fix_galactica(reply)
  81. return reply, reply, 'Only applicable for gpt4chan.'
  82. elif model_name.lower().startswith('gpt4chan'):
  83. reply = fix_gpt4chan(reply)
  84. return reply, 'Only applicable for galactica models.', generate_html(reply)
  85. else:
  86. return reply, 'Only applicable for galactica models.', 'Only applicable for gpt4chan.'
  87. # Choosing the default model
  88. if args.model is not None:
  89. model_name = args.model
  90. else:
  91. if len(available_models) == 0:
  92. print("No models are available! Please download at least one.")
  93. exit(0)
  94. elif len(available_models) == 1:
  95. i = 0
  96. else:
  97. print("The following models are available:\n")
  98. for i,model in enumerate(available_models):
  99. print(f"{i+1}. {model}")
  100. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  101. i = int(input())-1
  102. model_name = available_models[i]
  103. model, tokenizer = load_model(model_name)
  104. if model_name.startswith('gpt4chan'):
  105. default_text = "-----\n--- 865467536\nInput text\n--- 865467537\n"
  106. else:
  107. default_text = "Common sense questions and answers\n\nQuestion: \nFactual answer:"
  108. if args.notebook:
  109. with gr.Blocks() as interface:
  110. gr.Markdown(
  111. f"""
  112. # Text generation lab
  113. Generate text using Large Language Models.
  114. """
  115. )
  116. with gr.Tab('Raw'):
  117. textbox = gr.Textbox(value=default_text, lines=23)
  118. with gr.Tab('Markdown'):
  119. markdown = gr.Markdown()
  120. with gr.Tab('HTML'):
  121. html = gr.HTML()
  122. btn = gr.Button("Generate")
  123. with gr.Row():
  124. with gr.Column():
  125. temp_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Temperature', value=0.7)
  126. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_length', value=200)
  127. with gr.Column():
  128. preset_menu = gr.Dropdown(choices=available_presets, value="NovelAI-Sphinx Moth", label='Preset')
  129. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  130. btn.click(generate_reply, [textbox, temp_slider, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=False)
  131. else:
  132. with gr.Blocks() as interface:
  133. gr.Markdown(
  134. f"""
  135. # Text generation lab
  136. Generate text using Large Language Models.
  137. """
  138. )
  139. with gr.Row():
  140. with gr.Column():
  141. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  142. temp_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Temperature', value=0.7)
  143. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_length', value=200)
  144. preset_menu = gr.Dropdown(choices=available_presets, value="NovelAI-Sphinx Moth", label='Preset')
  145. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  146. btn = gr.Button("Generate")
  147. with gr.Column():
  148. with gr.Tab('Raw'):
  149. output_textbox = gr.Textbox(value=default_text, lines=15, label='Output')
  150. with gr.Tab('Markdown'):
  151. markdown = gr.Markdown()
  152. with gr.Tab('HTML'):
  153. html = gr.HTML()
  154. btn.click(generate_reply, [textbox, temp_slider, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=True)
  155. interface.launch(share=False, server_name="0.0.0.0")