server.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import os
  2. import re
  3. import time
  4. import glob
  5. from sys import exit
  6. import torch
  7. import argparse
  8. import gradio as gr
  9. import transformers
  10. from transformers import AutoTokenizer
  11. from transformers import GPTJForCausalLM, AutoModelForCausalLM, AutoModelForSeq2SeqLM, OPTForCausalLM, T5Tokenizer, T5ForConditionalGeneration, GPTJModel, AutoModel
  12. parser = argparse.ArgumentParser()
  13. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  14. 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.')
  15. args = parser.parse_args()
  16. loaded_preset = None
  17. available_models = sorted(set(map(lambda x : x.split('/')[-1].replace('.pt', ''), glob.glob("models/*[!\.][!t][!x][!t]")+ glob.glob("torch-dumps/*[!\.][!t][!x][!t]"))))
  18. def load_model(model_name):
  19. print(f"Loading {model_name}...")
  20. t0 = time.time()
  21. # Loading the model
  22. if os.path.exists(f"torch-dumps/{model_name}.pt"):
  23. print("Loading in .pt format...")
  24. model = torch.load(f"torch-dumps/{model_name}.pt").cuda()
  25. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')):
  26. if any(size in model_name for size in ('13b', '20b', '30b')):
  27. model = AutoModelForCausalLM.from_pretrained(f"models/{model_name}", device_map='auto', load_in_8bit=True)
  28. else:
  29. model = AutoModelForCausalLM.from_pretrained(f"models/{model_name}", low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  30. elif model_name in ['gpt-j-6B']:
  31. model = AutoModelForCausalLM.from_pretrained(f"models/{model_name}", low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  32. elif model_name in ['flan-t5', 't5-large']:
  33. model = T5ForConditionalGeneration.from_pretrained(f"models/{model_name}").cuda()
  34. else:
  35. model = AutoModelForCausalLM.from_pretrained(f"models/{model_name}", low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  36. # Loading the tokenizer
  37. if model_name.startswith('gpt4chan'):
  38. tokenizer = AutoTokenizer.from_pretrained("models/gpt-j-6B/")
  39. elif model_name in ['flan-t5']:
  40. tokenizer = T5Tokenizer.from_pretrained(f"models/{model_name}/")
  41. else:
  42. tokenizer = AutoTokenizer.from_pretrained(f"models/{model_name}/")
  43. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  44. return model, tokenizer
  45. # Removes empty replies from gpt4chan outputs
  46. def fix_gpt4chan(s):
  47. for i in range(10):
  48. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  49. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  50. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  51. return s
  52. def generate_reply(question, temperature, max_length, inference_settings, selected_model):
  53. global model, tokenizer, model_name, loaded_preset, preset
  54. if selected_model != model_name:
  55. model_name = selected_model
  56. model = None
  57. tokenier = None
  58. torch.cuda.empty_cache()
  59. model, tokenizer = load_model(model_name)
  60. if inference_settings != loaded_preset:
  61. with open(f'presets/{inference_settings}.txt', 'r') as infile:
  62. preset = infile.read()
  63. loaded_preset = inference_settings
  64. torch.cuda.empty_cache()
  65. input_text = question
  66. input_ids = tokenizer.encode(str(input_text), return_tensors='pt').cuda()
  67. output = eval(f"model.generate(input_ids, {preset}).cuda()")
  68. reply = tokenizer.decode(output[0], skip_special_tokens=True)
  69. if model_name.startswith('gpt4chan'):
  70. reply = fix_gpt4chan(reply)
  71. if model_name.lower().startswith('galactica'):
  72. return reply, reply
  73. else:
  74. return reply, ''
  75. # Choosing the default model
  76. if args.model is not None:
  77. model_name = args.model
  78. else:
  79. if len(available_models == 0):
  80. print("No models are available! Please download at least one.")
  81. exit(0)
  82. elif len(available_models) == 1:
  83. i = 0
  84. else:
  85. print("The following models are available:\n")
  86. for i,model in enumerate(available_models):
  87. print(f"{i+1}. {model}")
  88. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  89. i = int(input())-1
  90. model_name = available_models[i]
  91. model, tokenizer = load_model(model_name)
  92. if model_name.startswith('gpt4chan'):
  93. default_text = "-----\n--- 865467536\nInput text\n--- 865467537\n"
  94. else:
  95. default_text = "Common sense questions and answers\n\nQuestion: \nFactual answer:"
  96. if args.notebook:
  97. with gr.Blocks() as interface:
  98. gr.Markdown(
  99. f"""
  100. # Text generation lab
  101. Generate text using Large Language Models.
  102. """
  103. )
  104. textbox = gr.Textbox(value=default_text, lines=23)
  105. temp_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Temperature', value=0.7)
  106. length_slider = gr.Slider(minimum=1, maximum=2000, step=1, label='max_length', value=200)
  107. preset_menu = gr.Dropdown(choices=list(map(lambda x : x.split('/')[-1].split('.')[0], glob.glob("presets/*.txt"))), value="Default", label='Preset')
  108. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  109. btn = gr.Button("Generate")
  110. markdown = gr.Markdown()
  111. btn.click(generate_reply, [textbox, temp_slider, length_slider, preset_menu, model_menu], [textbox, markdown], show_progress=False)
  112. else:
  113. interface = gr.Interface(
  114. generate_reply,
  115. inputs=[
  116. gr.Textbox(value=default_text, lines=15),
  117. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Temperature', value=0.7),
  118. gr.Slider(minimum=1, maximum=2000, step=1, label='max_length', value=200),
  119. gr.Dropdown(choices=list(map(lambda x : x.split('/')[-1].split('.')[0], glob.glob("presets/*.txt"))), value="Default", label='Preset'),
  120. gr.Dropdown(choices=available_models, value=model_name, label='Model'),
  121. ],
  122. outputs=[
  123. gr.Textbox(placeholder="", lines=15),
  124. gr.Markdown()
  125. ],
  126. title="Text generation lab",
  127. description=f"Generate text using Large Language Models.",
  128. )
  129. interface.launch(share=False, server_name="0.0.0.0")