server.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import re
  2. import time
  3. import glob
  4. from sys import exit
  5. import torch
  6. import argparse
  7. import json
  8. from pathlib import Path
  9. import gradio as gr
  10. import transformers
  11. from html_generator import *
  12. from transformers import AutoTokenizer, AutoModelForCausalLM
  13. import warnings
  14. import gc
  15. from tqdm import tqdm
  16. transformers.logging.set_verbosity_error()
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  19. parser.add_argument('--notebook', action='store_true', help='Launch the web UI in notebook mode, where the output is written to the same text box as the input.')
  20. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  21. parser.add_argument('--cai-chat', action='store_true', help='Launch the web UI in chat mode with a style similar to Character.AI\'s. If the file profile.png or profile.jpg exists in the same folder as server.py, this image will be used as the bot\'s profile picture.')
  22. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  23. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  24. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  25. parser.add_argument('--disk', action='store_true', help='If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.')
  26. parser.add_argument('--max-gpu-memory', type=int, help='Maximum memory in GiB to allocate to the GPU when loading the model. This is useful if you get out of memory errors while trying to generate text. Must be an integer number.')
  27. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This slightly improves the text generation performance.')
  28. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  29. parser.add_argument('--no-listen', action='store_true', help='Make the web UI unreachable from your local network.')
  30. parser.add_argument('--share', action='store_true', help='Create a public URL. This is useful for running the web UI on Google Colab or similar.')
  31. args = parser.parse_args()
  32. loaded_preset = None
  33. available_models = sorted(set([item.replace('.pt', '') for item in map(lambda x : str(x.name), list(Path('models/').glob('*'))+list(Path('torch-dumps/').glob('*'))) if not item.endswith('.txt')]), key=str.lower)
  34. available_presets = sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  35. available_characters = sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  36. settings = {
  37. 'max_new_tokens': 200,
  38. 'max_new_tokens_min': 1,
  39. 'max_new_tokens_max': 2000,
  40. 'preset': 'NovelAI-Sphinx Moth',
  41. 'name1': 'Person 1',
  42. 'name2': 'Person 2',
  43. 'context': 'This is a conversation between two people.',
  44. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  45. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  46. 'stop_at_newline': True,
  47. 'history_size': 8,
  48. 'history_size_min': 0,
  49. 'history_size_max': 64,
  50. 'preset_pygmalion': 'Pygmalion',
  51. 'name1_pygmalion': 'You',
  52. 'name2_pygmalion': 'Kawaii',
  53. 'context_pygmalion': 'This is a conversation between two people.\n<START>',
  54. 'stop_at_newline_pygmalion': False,
  55. }
  56. if args.settings is not None and Path(args.settings).exists():
  57. with open(Path(args.settings), 'r') as f:
  58. new_settings = json.load(f)
  59. for item in new_settings:
  60. if item in settings:
  61. settings[item] = new_settings[item]
  62. def load_model(model_name):
  63. print(f"Loading {model_name}...")
  64. t0 = time.time()
  65. # Default settings
  66. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.max_gpu_memory is not None):
  67. if Path(f"torch-dumps/{model_name}.pt").exists():
  68. print("Loading in .pt format...")
  69. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  70. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  71. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  72. else:
  73. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  74. # Custom
  75. else:
  76. settings = ["low_cpu_mem_usage=True"]
  77. command = "AutoModelForCausalLM.from_pretrained"
  78. if args.cpu:
  79. settings.append("torch_dtype=torch.float32")
  80. else:
  81. settings.append("device_map='auto'")
  82. if args.max_gpu_memory is not None:
  83. settings.append(f"max_memory={{0: '{args.max_gpu_memory}GiB', 'cpu': '99GiB'}}")
  84. if args.disk:
  85. settings.append("offload_folder='cache'")
  86. if args.load_in_8bit:
  87. settings.append("load_in_8bit=True")
  88. else:
  89. settings.append("torch_dtype=torch.float16")
  90. settings = ', '.join(set(settings))
  91. command = f"{command}(Path(f'models/{model_name}'), {settings})"
  92. model = eval(command)
  93. # Loading the tokenizer
  94. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  95. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  96. else:
  97. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  98. tokenizer.truncation_side = 'left'
  99. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  100. return model, tokenizer
  101. # Removes empty replies from gpt4chan outputs
  102. def fix_gpt4chan(s):
  103. for i in range(10):
  104. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  105. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  106. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  107. return s
  108. # Fix the LaTeX equations in galactica
  109. def fix_galactica(s):
  110. s = s.replace(r'\[', r'$')
  111. s = s.replace(r'\]', r'$')
  112. s = s.replace(r'\(', r'$')
  113. s = s.replace(r'\)', r'$')
  114. s = s.replace(r'$$', r'$')
  115. return s
  116. def encode(prompt, tokens):
  117. if not args.cpu:
  118. torch.cuda.empty_cache()
  119. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens).cuda()
  120. else:
  121. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens)
  122. return input_ids
  123. def decode(output_ids):
  124. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  125. reply = reply.replace(r'<|endoftext|>', '')
  126. return reply
  127. def formatted_outputs(reply, model_name):
  128. if not (args.chat or args.cai_chat):
  129. if model_name.lower().startswith('galactica'):
  130. reply = fix_galactica(reply)
  131. return reply, reply, generate_basic_html(reply)
  132. elif model_name.lower().startswith('gpt4chan'):
  133. reply = fix_gpt4chan(reply)
  134. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  135. else:
  136. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  137. else:
  138. return reply
  139. def generate_reply(question, tokens, inference_settings, selected_model, eos_token=None):
  140. global model, tokenizer, model_name, loaded_preset, preset
  141. if selected_model != model_name:
  142. model_name = selected_model
  143. model = None
  144. tokenizer = None
  145. if not args.cpu:
  146. gc.collect()
  147. torch.cuda.empty_cache()
  148. model, tokenizer = load_model(model_name)
  149. if inference_settings != loaded_preset:
  150. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  151. preset = infile.read()
  152. loaded_preset = inference_settings
  153. cuda = "" if args.cpu else ".cuda()"
  154. n = None if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  155. input_ids = encode(question, tokens)
  156. # Generate the entire reply at once
  157. if args.no_stream:
  158. output = eval(f"model.generate(input_ids, eos_token_id={n}, {preset}){cuda}")
  159. reply = decode(output[0])
  160. yield formatted_outputs(reply, model_name)
  161. # Generate the reply 1 token at a time
  162. else:
  163. yield formatted_outputs(question, model_name)
  164. preset = preset.replace('max_new_tokens=tokens', 'max_new_tokens=1')
  165. for i in tqdm(range(tokens)):
  166. output = eval(f"model.generate(input_ids, {preset}){cuda}")
  167. reply = decode(output[0])
  168. if eos_token is not None and reply[-1] == eos_token:
  169. break
  170. yield formatted_outputs(reply, model_name)
  171. input_ids = output
  172. # Choosing the default model
  173. if args.model is not None:
  174. model_name = args.model
  175. else:
  176. if len(available_models) == 0:
  177. print("No models are available! Please download at least one.")
  178. exit(0)
  179. elif len(available_models) == 1:
  180. i = 0
  181. else:
  182. print("The following models are available:\n")
  183. for i,model in enumerate(available_models):
  184. print(f"{i+1}. {model}")
  185. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  186. i = int(input())-1
  187. print()
  188. model_name = available_models[i]
  189. model, tokenizer = load_model(model_name)
  190. # UI settings
  191. if model_name.lower().startswith('gpt4chan'):
  192. default_text = settings['prompt_gpt4chan']
  193. else:
  194. default_text = settings['prompt']
  195. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  196. css = ".my-4 {margin-top: 0} .py-6 {padding-top: 2.5rem}"
  197. if args.chat or args.cai_chat:
  198. history = []
  199. character = None
  200. # This gets the new line characters right.
  201. def clean_chat_message(text):
  202. text = text.replace('\n', '\n\n')
  203. text = re.sub(r"\n{3,}", "\n\n", text)
  204. text = text.strip()
  205. return text
  206. def generate_chat_prompt(text, tokens, name1, name2, context, history_size):
  207. text = clean_chat_message(text)
  208. rows = [f"{context.strip()}\n"]
  209. i = len(history)-1
  210. count = 0
  211. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < 2048-tokens:
  212. rows.insert(1, f"{name2}: {history[i][1].strip()}\n")
  213. count += 1
  214. if not (i == 0 and len(history[i][0]) == 0):
  215. rows.insert(1, f"{name1}: {history[i][0].strip()}\n")
  216. count += 1
  217. i -= 1
  218. if history_size != 0 and count >= history_size:
  219. break
  220. rows.append(f"{name1}: {text}\n")
  221. rows.append(f"{name2}:")
  222. while len(rows) > 3 and len(encode(''.join(rows), tokens)[0]) >= 2048-tokens:
  223. rows.pop(1)
  224. rows.pop(1)
  225. question = ''.join(rows)
  226. return question
  227. def chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  228. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size)
  229. history.append(['', ''])
  230. eos_token = '\n' if check else None
  231. for reply in generate_reply(question, tokens, inference_settings, selected_model, eos_token=eos_token):
  232. next_character_found = False
  233. previous_idx = [m.start() for m in re.finditer(f"(^|\n){name2}:", question)]
  234. idx = [m.start() for m in re.finditer(f"(^|\n){name2}:", reply)]
  235. idx = idx[len(previous_idx)-1]
  236. reply = reply[idx + len(f"\n{name2}:"):]
  237. if check:
  238. reply = reply.split('\n')[0].strip()
  239. else:
  240. idx = reply.find(f"\n{name1}:")
  241. if idx != -1:
  242. reply = reply[:idx]
  243. next_character_found = True
  244. reply = clean_chat_message(reply)
  245. history[-1] = [text, reply]
  246. if next_character_found:
  247. break
  248. # Prevent the chat log from flashing if something like "\nYo" is generated just
  249. # before "\nYou:" is completed
  250. tmp = f"\n{name1}:"
  251. next_character_substring_found = False
  252. for j in range(1, len(tmp)):
  253. if reply[-j:] == tmp[:j]:
  254. next_character_substring_found = True
  255. if not next_character_substring_found:
  256. yield history
  257. yield history
  258. def cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  259. for history in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  260. yield generate_chat_html(history, name1, name2, character)
  261. def remove_last_message(name1, name2):
  262. history.pop()
  263. if args.cai_chat:
  264. return generate_chat_html(history, name1, name2, character)
  265. else:
  266. return history
  267. def clear():
  268. global history
  269. history = []
  270. def clear_html():
  271. return generate_chat_html([], "", "", character)
  272. def redraw_html(name1, name2):
  273. global history
  274. return generate_chat_html(history, name1, name2, character)
  275. def save_history():
  276. if not Path('logs').exists():
  277. Path('logs').mkdir()
  278. with open(Path('logs/conversation.json'), 'w') as f:
  279. f.write(json.dumps({'data': history}))
  280. return Path('logs/conversation.json')
  281. def load_history(file):
  282. global history
  283. history = json.loads(file.decode('utf-8'))['data']
  284. def load_character(_character, name1, name2):
  285. global history, character
  286. context = ""
  287. history = []
  288. if _character != 'None':
  289. character = _character
  290. with open(Path(f'characters/{_character}.json'), 'r') as f:
  291. data = json.loads(f.read())
  292. name2 = data['char_name']
  293. if 'char_persona' in data and data['char_persona'] != '':
  294. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  295. if 'world_scenario' in data and data['world_scenario'] != '':
  296. context += f"Scenario: {data['world_scenario']}\n"
  297. context = f"{context.strip()}\n<START>\n"
  298. if 'example_dialogue' in data and data['example_dialogue'] != '':
  299. context += f"{data['example_dialogue'].strip()}\n"
  300. if 'char_greeting' in data:
  301. history = [['', data['char_greeting']]]
  302. else:
  303. character = None
  304. context = settings['context_pygmalion']
  305. name2 = settings['name2_pygmalion']
  306. if args.cai_chat:
  307. return name2, context, generate_chat_html(history, name1, name2, character)
  308. else:
  309. return name2, context, history
  310. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  311. with gr.Blocks(css=css+".h-\[40vh\] {height: 66.67vh} .gradio-container {max-width: 800px; margin-left: auto; margin-right: auto}", analytics_enabled=False) as interface:
  312. if args.cai_chat:
  313. display1 = gr.HTML(value=generate_chat_html([], "", "", character))
  314. else:
  315. display1 = gr.Chatbot()
  316. textbox = gr.Textbox(lines=2, label='Input')
  317. btn = gr.Button("Generate")
  318. with gr.Row():
  319. btn2 = gr.Button("Clear history")
  320. stop = gr.Button("Stop")
  321. btn3 = gr.Button("Remove last message")
  322. with gr.Row():
  323. with gr.Column():
  324. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  325. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  326. with gr.Column():
  327. history_size_slider = gr.Slider(minimum=settings['history_size_min'], maximum=settings['history_size_max'], step=1, label='Chat history size (0 for no limit)', value=settings['history_size'])
  328. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Settings preset')
  329. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  330. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  331. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  332. with gr.Row():
  333. character_menu = gr.Dropdown(choices=["None"]+available_characters, value="None", label='Character')
  334. with gr.Row():
  335. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  336. with gr.Row():
  337. with gr.Column():
  338. gr.Markdown("Upload chat history")
  339. upload = gr.File(type='binary')
  340. with gr.Column():
  341. gr.Markdown("Download chat history")
  342. save_btn = gr.Button(value="Click me")
  343. download = gr.File()
  344. input_params = [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check, history_size_slider]
  345. if args.cai_chat:
  346. gen_event = btn.click(cai_chatbot_wrapper, input_params, display1, show_progress=args.no_stream, api_name="textgen")
  347. gen_event2 = textbox.submit(cai_chatbot_wrapper, input_params, display1, show_progress=args.no_stream)
  348. btn2.click(clear_html, [], display1, show_progress=False)
  349. else:
  350. gen_event = btn.click(chatbot_wrapper, input_params, display1, show_progress=args.no_stream, api_name="textgen")
  351. gen_event2 = textbox.submit(chatbot_wrapper, input_params, display1, show_progress=args.no_stream)
  352. btn2.click(lambda x: "", display1, display1, show_progress=False)
  353. btn2.click(clear)
  354. btn3.click(remove_last_message, [name1, name2], display1, show_progress=False)
  355. btn.click(lambda x: "", textbox, textbox, show_progress=False)
  356. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  357. stop.click(None, None, None, cancels=[gen_event, gen_event2])
  358. save_btn.click(save_history, inputs=[], outputs=[download])
  359. upload.upload(load_history, [upload], [])
  360. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display1])
  361. if args.cai_chat:
  362. upload.upload(redraw_html, [name1, name2], [display1])
  363. else:
  364. upload.upload(lambda : history, [], [display1])
  365. elif args.notebook:
  366. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  367. gr.Markdown(description)
  368. with gr.Tab('Raw'):
  369. textbox = gr.Textbox(value=default_text, lines=23)
  370. with gr.Tab('Markdown'):
  371. markdown = gr.Markdown()
  372. with gr.Tab('HTML'):
  373. html = gr.HTML()
  374. btn = gr.Button("Generate")
  375. stop = gr.Button("Stop")
  376. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  377. with gr.Row():
  378. with gr.Column():
  379. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  380. with gr.Column():
  381. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  382. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  383. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream)
  384. stop.click(None, None, None, cancels=[gen_event, gen_event2])
  385. else:
  386. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  387. gr.Markdown(description)
  388. with gr.Row():
  389. with gr.Column():
  390. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  391. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  392. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  393. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  394. btn = gr.Button("Generate")
  395. with gr.Row():
  396. with gr.Column():
  397. cont = gr.Button("Continue")
  398. with gr.Column():
  399. stop = gr.Button("Stop")
  400. with gr.Column():
  401. with gr.Tab('Raw'):
  402. output_textbox = gr.Textbox(lines=15, label='Output')
  403. with gr.Tab('Markdown'):
  404. markdown = gr.Markdown()
  405. with gr.Tab('HTML'):
  406. html = gr.HTML()
  407. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  408. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  409. cont_event = cont.click(generate_reply, [output_textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  410. stop.click(None, None, None, cancels=[gen_event, gen_event2, cont_event])
  411. interface.queue()
  412. if args.no_listen:
  413. interface.launch(share=args.share)
  414. else:
  415. interface.launch(share=args.share, server_name="0.0.0.0")