server.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. import re
  2. import gc
  3. import time
  4. import glob
  5. import torch
  6. import argparse
  7. import json
  8. import io
  9. import base64
  10. import sys
  11. import os
  12. from pathlib import Path
  13. from PIL import Image
  14. import copy
  15. import gradio as gr
  16. import warnings
  17. from tqdm import tqdm
  18. import transformers
  19. from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
  20. from modules.html_generator import *
  21. from modules.ui import *
  22. from modules.stopping_criteria import _SentinelTokenStoppingCriteria
  23. transformers.logging.set_verbosity_error()
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  26. 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.')
  27. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  28. 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 img_bot.png or img_bot.jpg exists in the same folder as server.py, this image will be used as the bot\'s profile picture. Similarly, img_me.png or img_me.jpg will be used as your profile picture.')
  29. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  30. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  31. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  32. 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.')
  33. parser.add_argument('--disk-cache-dir', type=str, help='Directory to save the disk cache to. Defaults to "cache/".')
  34. parser.add_argument('--gpu-memory', type=int, help='Maximum GPU memory in GiB to allocate. This is useful if you get out of memory errors while trying to generate text. Must be an integer number.')
  35. parser.add_argument('--cpu-memory', type=int, help='Maximum CPU memory in GiB to allocate for offloaded weights. Must be an integer number. Defaults to 99.')
  36. parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.')
  37. parser.add_argument('--nvme-offload-dir', type=str, help='Directory to use for DeepSpeed ZeRO-3 NVME offloading.')
  38. parser.add_argument('--local_rank', type=int, default=0, help='Optional argument for DeepSpeed distributed setups.')
  39. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This improves the text generation performance.')
  40. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  41. parser.add_argument('--extensions', type=str, help='The list of extensions to load. If you want to load more than one extension, write the names separated by commas and between quotation marks, "like,this".')
  42. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  43. parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
  44. 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.')
  45. parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.')
  46. args = parser.parse_args()
  47. if (args.chat or args.cai_chat) and not args.no_stream:
  48. print("Warning: chat mode currently becomes somewhat slower with text streaming on.\nConsider starting the web UI with the --no-stream option.\n")
  49. settings = {
  50. 'max_new_tokens': 200,
  51. 'max_new_tokens_min': 1,
  52. 'max_new_tokens_max': 2000,
  53. 'preset': 'NovelAI-Sphinx Moth',
  54. 'name1': 'Person 1',
  55. 'name2': 'Person 2',
  56. 'context': 'This is a conversation between two people.',
  57. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  58. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  59. 'stop_at_newline': True,
  60. 'history_size': 0,
  61. 'history_size_min': 0,
  62. 'history_size_max': 64,
  63. 'preset_pygmalion': 'Pygmalion',
  64. 'name1_pygmalion': 'You',
  65. 'name2_pygmalion': 'Kawaii',
  66. 'context_pygmalion': "Kawaii's persona: Kawaii is a cheerful person who loves to make others smile. She is an optimist who loves to spread happiness and positivity wherever she goes.\n<START>",
  67. 'stop_at_newline_pygmalion': False,
  68. }
  69. if args.settings is not None and Path(args.settings).exists():
  70. new_settings = json.loads(open(Path(args.settings), 'r').read())
  71. for item in new_settings:
  72. settings[item] = new_settings[item]
  73. if args.deepspeed:
  74. import deepspeed
  75. from transformers.deepspeed import HfDeepSpeedConfig, is_deepspeed_zero3_enabled
  76. # Distributed setup
  77. if args.local_rank is not None:
  78. local_rank = args.local_rank
  79. else:
  80. local_rank = int(os.getenv("LOCAL_RANK", "0"))
  81. world_size = int(os.getenv("WORLD_SIZE", "1"))
  82. torch.cuda.set_device(local_rank)
  83. deepspeed.init_distributed()
  84. # DeepSpeed configration
  85. # https://huggingface.co/docs/transformers/main_classes/deepspeed
  86. train_batch_size = 1 * world_size
  87. if args.nvme_offload_dir:
  88. ds_config = {
  89. "fp16": {
  90. "enabled": True,
  91. },
  92. "bf16": {
  93. "enabled": False,
  94. },
  95. "zero_optimization": {
  96. "stage": 3,
  97. "offload_param": {
  98. "device": "nvme",
  99. "nvme_path": args.nvme_offload_dir,
  100. "pin_memory": True,
  101. "buffer_count": 5,
  102. "buffer_size": 1e9,
  103. "max_in_cpu": 1e9
  104. },
  105. "overlap_comm": True,
  106. "reduce_bucket_size": "auto",
  107. "contiguous_gradients": True,
  108. "sub_group_size": 1e8,
  109. "stage3_prefetch_bucket_size": "auto",
  110. "stage3_param_persistence_threshold": "auto",
  111. "stage3_max_live_parameters": "auto",
  112. "stage3_max_reuse_distance": "auto",
  113. },
  114. "aio": {
  115. "block_size": 262144,
  116. "queue_depth": 32,
  117. "thread_count": 1,
  118. "single_submit": False,
  119. "overlap_events": True
  120. },
  121. "steps_per_print": 2000,
  122. "train_batch_size": train_batch_size,
  123. "train_micro_batch_size_per_gpu": 1,
  124. "wall_clock_breakdown": False
  125. }
  126. else:
  127. ds_config = {
  128. "fp16": {
  129. "enabled": True,
  130. },
  131. "bf16": {
  132. "enabled": False,
  133. },
  134. "zero_optimization": {
  135. "stage": 3,
  136. "offload_param": {
  137. "device": "cpu",
  138. "pin_memory": True
  139. },
  140. "overlap_comm": True,
  141. "contiguous_gradients": True,
  142. "reduce_bucket_size": "auto",
  143. "stage3_prefetch_bucket_size": "auto",
  144. "stage3_param_persistence_threshold": "auto",
  145. "stage3_max_live_parameters": "auto",
  146. "stage3_max_reuse_distance": "auto",
  147. },
  148. "steps_per_print": 2000,
  149. "train_batch_size": train_batch_size,
  150. "train_micro_batch_size_per_gpu": 1,
  151. "wall_clock_breakdown": False
  152. }
  153. dschf = HfDeepSpeedConfig(ds_config) # Keep this object alive for the Transformers integration
  154. def load_model(model_name):
  155. print(f"Loading {model_name}...")
  156. t0 = time.time()
  157. # Default settings
  158. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.gpu_memory is not None or args.cpu_memory is not None or args.deepspeed):
  159. if Path(f"torch-dumps/{model_name}.pt").exists():
  160. print("Loading in .pt format...")
  161. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  162. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  163. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  164. else:
  165. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  166. # DeepSpeed ZeRO-3
  167. elif args.deepspeed:
  168. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}", no_split_module_classes=["GPTJBlock"]))
  169. model = deepspeed.initialize(model=model,
  170. config_params=ds_config,
  171. model_parameters=None,
  172. optimizer=None,
  173. lr_scheduler=None)[0]
  174. model.module.eval() # Inference
  175. print(f"DeepSpeed ZeRO-3 is enabled: {is_deepspeed_zero3_enabled()}")
  176. # Custom
  177. else:
  178. command = "AutoModelForCausalLM.from_pretrained"
  179. settings = []
  180. if args.cpu:
  181. settings.append("low_cpu_mem_usage=True")
  182. settings.append("torch_dtype=torch.float32")
  183. else:
  184. settings.append("device_map='auto'")
  185. settings.append("load_in_8bit=True" if args.load_in_8bit else "torch_dtype=torch.float16")
  186. if args.gpu_memory:
  187. settings.append(f"max_memory={{0: '{args.gpu_memory or '99'}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  188. elif not args.load_in_8bit:
  189. total_mem = (torch.cuda.get_device_properties(0).total_memory/(1024*1024))
  190. suggestion = round((total_mem-1000)/1000)*1000
  191. if total_mem-suggestion < 800:
  192. suggestion -= 1000
  193. suggestion = int(round(suggestion/1000))
  194. print(f"\033[1;32;1mAuto-assiging --gpu-memory {suggestion} for your GPU to try to prevent out-of-memory errors.\nYou can manually set other values.\033[0;37;0m")
  195. settings.append(f"max_memory={{0: '{suggestion}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  196. if args.disk:
  197. settings.append(f"offload_folder='{args.disk_cache_dir or 'cache'}'")
  198. settings = ', '.join(set(settings))
  199. command = f"{command}(Path(f'models/{model_name}'), {settings})"
  200. model = eval(command)
  201. # Loading the tokenizer
  202. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  203. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  204. else:
  205. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  206. tokenizer.truncation_side = 'left'
  207. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  208. return model, tokenizer
  209. # Removes empty replies from gpt4chan outputs
  210. def fix_gpt4chan(s):
  211. for i in range(10):
  212. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  213. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  214. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  215. return s
  216. # Fix the LaTeX equations in galactica
  217. def fix_galactica(s):
  218. s = s.replace(r'\[', r'$')
  219. s = s.replace(r'\]', r'$')
  220. s = s.replace(r'\(', r'$')
  221. s = s.replace(r'\)', r'$')
  222. s = s.replace(r'$$', r'$')
  223. return s
  224. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  225. if args.cpu:
  226. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens_to_generate, add_special_tokens=add_special_tokens)
  227. else:
  228. torch.cuda.empty_cache()
  229. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens_to_generate, add_special_tokens=add_special_tokens).cuda()
  230. return input_ids
  231. def decode(output_ids):
  232. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  233. reply = reply.replace(r'<|endoftext|>', '')
  234. return reply
  235. def formatted_outputs(reply, model_name):
  236. if not (args.chat or args.cai_chat):
  237. if model_name.lower().startswith('galactica'):
  238. reply = fix_galactica(reply)
  239. return reply, reply, generate_basic_html(reply)
  240. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  241. reply = fix_gpt4chan(reply)
  242. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  243. else:
  244. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  245. else:
  246. return reply
  247. def generate_reply(question, tokens, inference_settings, selected_model, eos_token=None, stopping_string=None):
  248. global model, tokenizer, model_name, loaded_preset, preset
  249. original_question = question
  250. if not (args.chat or args.cai_chat):
  251. question = apply_extensions(question, "input")
  252. if args.verbose:
  253. print(f"\n\n{question}\n--------------------\n")
  254. if selected_model != model_name:
  255. model_name = selected_model
  256. model = tokenizer = None
  257. if not args.cpu:
  258. gc.collect()
  259. torch.cuda.empty_cache()
  260. model, tokenizer = load_model(model_name)
  261. if inference_settings != loaded_preset:
  262. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  263. preset = infile.read()
  264. loaded_preset = inference_settings
  265. cuda = "" if args.cpu else ".cuda()"
  266. n = tokenizer.eos_token_id if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  267. if args.deepspeed:
  268. input_ids = encode(question, tokens).to(device=local_rank)
  269. else:
  270. input_ids = encode(question, tokens)
  271. if stopping_string is not None:
  272. # The stopping_criteria code below was copied from
  273. # https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py
  274. t = encode(stopping_string, 0, add_special_tokens=False)
  275. stopping_criteria_list = transformers.StoppingCriteriaList([
  276. _SentinelTokenStoppingCriteria(
  277. sentinel_token_ids=t,
  278. starting_idx=len(input_ids[0])
  279. )
  280. ])
  281. else:
  282. stopping_criteria_list = None
  283. # Generate the entire reply at once
  284. if args.no_stream:
  285. t0 = time.time()
  286. if args.deepspeed:
  287. with torch.no_grad():
  288. output = eval(f"model.generate(input_ids, eos_token_id={n}, stopping_criteria=stopping_criteria_list, {preset})")
  289. else:
  290. output = eval(f"model.generate(input_ids, eos_token_id={n}, stopping_criteria=stopping_criteria_list, {preset}){cuda}")
  291. reply = decode(output[0])
  292. t1 = time.time()
  293. print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output[0])-len(input_ids[0]))/(t1-t0):.2f} it/s)")
  294. if not (args.chat or args.cai_chat):
  295. reply = original_question + apply_extensions(reply[len(question):], "output")
  296. yield formatted_outputs(reply, model_name)
  297. # Generate the reply 1 token at a time
  298. else:
  299. yield formatted_outputs(original_question, model_name)
  300. preset = preset.replace('max_new_tokens=tokens', 'max_new_tokens=8')
  301. for i in tqdm(range(tokens//8+1)):
  302. if args.deepspeed:
  303. with torch.no_grad():
  304. output = eval(f"model.generate(input_ids, eos_token_id={n}, stopping_criteria=stopping_criteria_list, {preset})")
  305. else:
  306. output = eval(f"model.generate(input_ids, eos_token_id={n}, stopping_criteria=stopping_criteria_list, {preset}){cuda}")
  307. reply = decode(output[0])
  308. if not (args.chat or args.cai_chat):
  309. reply = original_question + apply_extensions(reply[len(question):], "output")
  310. yield formatted_outputs(reply, model_name)
  311. input_ids = output
  312. if output[0][-1] == n:
  313. break
  314. def apply_extensions(text, typ):
  315. global available_extensions, extension_state
  316. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  317. if extension_state[ext][0] == True:
  318. ext_string = f"extensions.{ext}.script"
  319. if typ == "input" and hasattr(eval(ext_string), "input_modifier"):
  320. text = eval(f"{ext_string}.input_modifier(text)")
  321. elif typ == "output" and hasattr(eval(ext_string), "output_modifier"):
  322. text = eval(f"{ext_string}.output_modifier(text)")
  323. elif typ == "bot_prefix" and hasattr(eval(ext_string), "bot_prefix_modifier"):
  324. text = eval(f"{ext_string}.bot_prefix_modifier(text)")
  325. return text
  326. def update_extensions_parameters(*kwargs):
  327. i = 0
  328. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  329. if extension_state[ext][0] == True:
  330. params = eval(f"extensions.{ext}.script.params")
  331. for param in params:
  332. if len(kwargs) >= i+1:
  333. params[param] = eval(f"kwargs[{i}]")
  334. i += 1
  335. def create_extensions_block():
  336. extensions_ui_elements = []
  337. default_values = []
  338. gr.Markdown('## Extensions parameters')
  339. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  340. if extension_state[ext][0] == True:
  341. params = eval(f"extensions.{ext}.script.params")
  342. for param in params:
  343. _id = f"{ext}-{param}"
  344. default_value = settings[_id] if _id in settings else params[param]
  345. default_values.append(default_value)
  346. if type(params[param]) == str:
  347. extensions_ui_elements.append(gr.Textbox(value=default_value, label=f"{ext}-{param}"))
  348. elif type(params[param]) in [int, float]:
  349. extensions_ui_elements.append(gr.Number(value=default_value, label=f"{ext}-{param}"))
  350. elif type(params[param]) == bool:
  351. extensions_ui_elements.append(gr.Checkbox(value=default_value, label=f"{ext}-{param}"))
  352. update_extensions_parameters(*default_values)
  353. btn_extensions = gr.Button("Apply")
  354. btn_extensions.click(update_extensions_parameters, [*extensions_ui_elements], [])
  355. def get_available_models():
  356. return 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)
  357. def get_available_presets():
  358. return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  359. def get_available_characters():
  360. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  361. def get_available_extensions():
  362. return sorted(set(map(lambda x : x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
  363. available_models = get_available_models()
  364. available_presets = get_available_presets()
  365. available_characters = get_available_characters()
  366. available_extensions = get_available_extensions()
  367. extension_state = {}
  368. if args.extensions is not None:
  369. for i,ext in enumerate(args.extensions.split(',')):
  370. if ext in available_extensions:
  371. print(f'Loading the extension "{ext}"... ', end='')
  372. ext_string = f"extensions.{ext}.script"
  373. exec(f"import {ext_string}")
  374. extension_state[ext] = [True, i]
  375. print(f'Ok.')
  376. # Choosing the default model
  377. if args.model is not None:
  378. model_name = args.model
  379. else:
  380. if len(available_models) == 0:
  381. print("No models are available! Please download at least one.")
  382. sys.exit(0)
  383. elif len(available_models) == 1:
  384. i = 0
  385. else:
  386. print("The following models are available:\n")
  387. for i,model in enumerate(available_models):
  388. print(f"{i+1}. {model}")
  389. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  390. i = int(input())-1
  391. print()
  392. model_name = available_models[i]
  393. model, tokenizer = load_model(model_name)
  394. loaded_preset = None
  395. # UI settings
  396. default_text = settings['prompt_gpt4chan'] if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) else settings['prompt']
  397. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  398. css = ".my-4 {margin-top: 0} .py-6 {padding-top: 2.5rem} #refresh-button {flex: none; margin: 0; padding: 0; min-width: 50px; border: none; box-shadow: none; border-radius: 0} #download-label, #upload-label {min-height: 0}"
  399. buttons = {}
  400. gen_events = []
  401. if args.chat or args.cai_chat:
  402. history = {'internal': [], 'visible': []}
  403. character = None
  404. # This gets the new line characters right.
  405. def clean_chat_message(text):
  406. text = text.replace('\n', '\n\n')
  407. text = re.sub(r"\n{3,}", "\n\n", text)
  408. text = text.strip()
  409. return text
  410. def generate_chat_prompt(text, tokens, name1, name2, context, history_size, impersonate=False):
  411. text = clean_chat_message(text)
  412. rows = [f"{context.strip()}\n"]
  413. i = len(history['internal'])-1
  414. count = 0
  415. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < 2048-tokens:
  416. rows.insert(1, f"{name2}: {history['internal'][i][1].strip()}\n")
  417. count += 1
  418. if not (history['internal'][i][0] == '<|BEGIN-VISIBLE-CHAT|>'):
  419. rows.insert(1, f"{name1}: {history['internal'][i][0].strip()}\n")
  420. count += 1
  421. i -= 1
  422. if history_size != 0 and count >= history_size:
  423. break
  424. if not impersonate:
  425. rows.append(f"{name1}: {text}\n")
  426. rows.append(apply_extensions(f"{name2}:", "bot_prefix"))
  427. limit = 3
  428. else:
  429. rows.append(f"{name1}:")
  430. limit = 2
  431. while len(rows) > limit and len(encode(''.join(rows), tokens)[0]) >= 2048-tokens:
  432. rows.pop(1)
  433. rows.pop(1)
  434. question = ''.join(rows)
  435. return question
  436. def extract_message_from_reply(question, reply, current, other, check, extensions=False):
  437. next_character_found = False
  438. substring_found = False
  439. previous_idx = [m.start() for m in re.finditer(f"(^|\n){current}:", question)]
  440. idx = [m.start() for m in re.finditer(f"(^|\n){current}:", reply)]
  441. idx = idx[len(previous_idx)-1]
  442. if extensions:
  443. reply = reply[idx + 1 + len(apply_extensions(f"{current}:", "bot_prefix")):]
  444. else:
  445. reply = reply[idx + 1 + len(f"{current}:"):]
  446. if check:
  447. reply = reply.split('\n')[0].strip()
  448. else:
  449. idx = reply.find(f"\n{other}:")
  450. if idx != -1:
  451. reply = reply[:idx]
  452. next_character_found = True
  453. reply = clean_chat_message(reply)
  454. # Detect if something like "\nYo" is generated just before
  455. # "\nYou:" is completed
  456. tmp = f"\n{other}:"
  457. for j in range(1, len(tmp)):
  458. if reply[-j:] == tmp[:j]:
  459. substring_found = True
  460. return reply, next_character_found, substring_found
  461. def chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  462. original_text = text
  463. text = apply_extensions(text, "input")
  464. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size)
  465. history['internal'].append(['', ''])
  466. history['visible'].append(['', ''])
  467. eos_token = '\n' if check else None
  468. for reply in generate_reply(question, tokens, inference_settings, selected_model, eos_token=eos_token, stopping_string=f"\n{name1}:"):
  469. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name2, name1, check, extensions=True)
  470. history['internal'][-1] = [text, reply]
  471. history['visible'][-1] = [original_text, apply_extensions(reply, "output")]
  472. if not substring_found:
  473. yield history['visible']
  474. if next_character_found:
  475. break
  476. yield history['visible']
  477. def impersonate_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  478. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size, impersonate=True)
  479. eos_token = '\n' if check else None
  480. for reply in generate_reply(question, tokens, inference_settings, selected_model, eos_token=eos_token, stopping_string=f"\n{name2}:"):
  481. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name1, name2, check, extensions=False)
  482. if not substring_found:
  483. yield apply_extensions(reply, "output")
  484. if next_character_found:
  485. break
  486. yield apply_extensions(reply, "output")
  487. def cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  488. for _history in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  489. yield generate_chat_html(_history, name1, name2, character)
  490. def regenerate_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  491. last = history['visible'].pop()
  492. history['internal'].pop()
  493. text = last[0]
  494. if args.cai_chat:
  495. for i in cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  496. yield i
  497. else:
  498. for i in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  499. yield i
  500. def remove_last_message(name1, name2):
  501. if not history['internal'][-1][0] == '<|BEGIN-VISIBLE-CHAT|>':
  502. last = history['visible'].pop()
  503. history['internal'].pop()
  504. else:
  505. last = ['', '']
  506. if args.cai_chat:
  507. return generate_chat_html(history['visible'], name1, name2, character), last[0]
  508. else:
  509. return history['visible'], last[0]
  510. def send_last_reply_to_input():
  511. if len(history['visible']) > 0:
  512. return history['visible'][-1][1]
  513. else:
  514. return ''
  515. def replace_last_reply(text, name1, name2):
  516. if len(history['visible']) > 0:
  517. history['visible'][-1][1] = text
  518. history['internal'][-1][1] = apply_extensions(text, "input")
  519. if args.cai_chat:
  520. return generate_chat_html(history['visible'], name1, name2, character)
  521. else:
  522. return history['visible']
  523. def clear_html():
  524. return generate_chat_html([], "", "", character)
  525. def clear_chat_log(_character, name1, name2):
  526. global history
  527. if _character != 'None':
  528. for i in range(len(history['internal'])):
  529. if '<|BEGIN-VISIBLE-CHAT|>' in history['internal'][i][0]:
  530. history['visible'] = [['', history['internal'][i][1]]]
  531. history['internal'] = history['internal'][:i+1]
  532. break
  533. else:
  534. history['internal'] = []
  535. history['visible'] = []
  536. if args.cai_chat:
  537. return generate_chat_html(history['visible'], name1, name2, character)
  538. else:
  539. return history['visible']
  540. def redraw_html(name1, name2):
  541. global history
  542. return generate_chat_html(history['visible'], name1, name2, character)
  543. def tokenize_dialogue(dialogue, name1, name2):
  544. _history = []
  545. dialogue = re.sub('<START>', '', dialogue)
  546. dialogue = re.sub('<start>', '', dialogue)
  547. dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue)
  548. dialogue = re.sub('(\n|^)\[CHARACTER\]:', f'\\1{name2}:', dialogue)
  549. idx = [m.start() for m in re.finditer(f"(^|\n)({name1}|{name2}):", dialogue)]
  550. if len(idx) == 0:
  551. return _history
  552. messages = []
  553. for i in range(len(idx)-1):
  554. messages.append(dialogue[idx[i]:idx[i+1]].strip())
  555. messages.append(dialogue[idx[-1]:].strip())
  556. entry = ['', '']
  557. for i in messages:
  558. if i.startswith(f'{name1}:'):
  559. entry[0] = i[len(f'{name1}:'):].strip()
  560. elif i.startswith(f'{name2}:'):
  561. entry[1] = i[len(f'{name2}:'):].strip()
  562. if not (len(entry[0]) == 0 and len(entry[1]) == 0):
  563. _history.append(entry)
  564. entry = ['', '']
  565. print(f"\033[1;32;1m\nDialogue tokenized to:\033[0;37;0m\n", end='')
  566. for row in _history:
  567. for column in row:
  568. print("\n")
  569. for line in column.strip().split('\n'):
  570. print("| "+line+"\n")
  571. print("|\n")
  572. print("------------------------------")
  573. return _history
  574. def save_history():
  575. if not Path('logs').exists():
  576. Path('logs').mkdir()
  577. with open(Path('logs/conversation.json'), 'w') as f:
  578. f.write(json.dumps({'data': history['internal'], 'data_visible': history['visible']}))
  579. return Path('logs/conversation.json')
  580. def upload_history(file, name1, name2):
  581. global history
  582. file = file.decode('utf-8')
  583. try:
  584. j = json.loads(file)
  585. if 'data' in j:
  586. history['internal'] = j['data']
  587. if 'data_visible' in j:
  588. history['visible'] = j['data_visible']
  589. else:
  590. history['visible'] = copy.deepcopy(history['internal'])
  591. # Compatibility with Pygmalion AI's official web UI
  592. elif 'chat' in j:
  593. history['internal'] = [':'.join(x.split(':')[1:]).strip() for x in j['chat']]
  594. if len(j['chat']) > 0 and j['chat'][0].startswith(f'{name2}:'):
  595. history['internal'] = [['<|BEGIN-VISIBLE-CHAT|>', history['internal'][0]]] + [[history['internal'][i], history['internal'][i+1]] for i in range(1, len(history['internal'])-1, 2)]
  596. else:
  597. history['internal'] = [[history['internal'][i], history['internal'][i+1]] for i in range(0, len(history['internal'])-1, 2)]
  598. except:
  599. history['internal'] = tokenize_dialogue(file, name1, name2)
  600. history['visible'] = copy.deepcopy(history['internal'])
  601. def load_character(_character, name1, name2):
  602. global history, character
  603. context = ""
  604. history['internal'] = []
  605. history['visible'] = []
  606. if _character != 'None':
  607. character = _character
  608. data = json.loads(open(Path(f'characters/{_character}.json'), 'r').read())
  609. name2 = data['char_name']
  610. if 'char_persona' in data and data['char_persona'] != '':
  611. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  612. if 'world_scenario' in data and data['world_scenario'] != '':
  613. context += f"Scenario: {data['world_scenario']}\n"
  614. context = f"{context.strip()}\n<START>\n"
  615. if 'example_dialogue' in data and data['example_dialogue'] != '':
  616. history['internal'] = tokenize_dialogue(data['example_dialogue'], name1, name2)
  617. if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0:
  618. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]]
  619. history['visible'] += [['', apply_extensions(data['char_greeting'], "output")]]
  620. else:
  621. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]]
  622. history['visible'] += [['', "Hello there!"]]
  623. else:
  624. character = None
  625. context = settings['context_pygmalion']
  626. name2 = settings['name2_pygmalion']
  627. if args.cai_chat:
  628. return name2, context, generate_chat_html(history['visible'], name1, name2, character)
  629. else:
  630. return name2, context, history['visible']
  631. def upload_character(json_file, img, tavern=False):
  632. json_file = json_file if type(json_file) == str else json_file.decode('utf-8')
  633. data = json.loads(json_file)
  634. outfile_name = data["char_name"]
  635. i = 1
  636. while Path(f'characters/{outfile_name}.json').exists():
  637. outfile_name = f'{data["char_name"]}_{i:03d}'
  638. i += 1
  639. if tavern:
  640. outfile_name = f'TavernAI-{outfile_name}'
  641. with open(Path(f'characters/{outfile_name}.json'), 'w') as f:
  642. f.write(json_file)
  643. if img is not None:
  644. img = Image.open(io.BytesIO(img))
  645. img.save(Path(f'characters/{outfile_name}.png'))
  646. print(f'New character saved to "characters/{outfile_name}.json".')
  647. return outfile_name
  648. def upload_tavern_character(img, name1, name2):
  649. _img = Image.open(io.BytesIO(img))
  650. _img.getexif()
  651. decoded_string = base64.b64decode(_img.info['chara'])
  652. _json = json.loads(decoded_string)
  653. _json = {"char_name": _json['name'], "char_persona": _json['description'], "char_greeting": _json["first_mes"], "example_dialogue": _json['mes_example'], "world_scenario": _json['scenario']}
  654. _json['example_dialogue'] = _json['example_dialogue'].replace('{{user}}', name1).replace('{{char}}', _json['char_name'])
  655. return upload_character(json.dumps(_json), img, tavern=True)
  656. def upload_your_profile_picture(img):
  657. img = Image.open(io.BytesIO(img))
  658. img.save(Path(f'img_me.png'))
  659. print(f'Profile picture saved to "img_me.png"')
  660. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  661. 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:
  662. if args.cai_chat:
  663. display = gr.HTML(value=generate_chat_html([], "", "", character))
  664. else:
  665. display = gr.Chatbot()
  666. textbox = gr.Textbox(label='Input')
  667. buttons["Generate"] = gr.Button("Generate")
  668. with gr.Row():
  669. buttons["Stop"] = gr.Button("Stop")
  670. buttons["Regenerate"] = gr.Button("Regenerate")
  671. buttons["Remove last"] = gr.Button("Remove last")
  672. buttons["Clear"] = gr.Button("Clear history")
  673. with gr.Row():
  674. buttons["Send last reply to input"] = gr.Button("Send last reply to input")
  675. buttons["Replace last reply"] = gr.Button("Replace last reply")
  676. buttons["Impersonate"] = gr.Button("Impersonate")
  677. with gr.Row():
  678. with gr.Column():
  679. 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'])
  680. with gr.Row():
  681. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  682. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  683. with gr.Column():
  684. history_size_slider = gr.Slider(minimum=settings['history_size_min'], maximum=settings['history_size_max'], step=1, label='Chat history size in prompt (0 for no limit)', value=settings['history_size'])
  685. with gr.Row():
  686. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Generation parameters preset')
  687. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  688. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  689. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  690. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  691. with gr.Row():
  692. character_menu = gr.Dropdown(choices=available_characters, value="None", label='Character')
  693. create_refresh_button(character_menu, lambda : None, lambda : {"choices": get_available_characters()}, "refresh-button")
  694. with gr.Row():
  695. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  696. with gr.Row():
  697. with gr.Tab('Chat history'):
  698. with gr.Row():
  699. with gr.Column():
  700. gr.Markdown('Upload')
  701. upload = gr.File(type='binary')
  702. with gr.Column():
  703. gr.Markdown('Download')
  704. download = gr.File()
  705. buttons["Download"] = gr.Button(value="Click me")
  706. with gr.Tab('Upload character'):
  707. with gr.Row():
  708. with gr.Column():
  709. gr.Markdown('1. Select the JSON file')
  710. upload_char = gr.File(type='binary')
  711. with gr.Column():
  712. gr.Markdown('2. Select your character\'s profile picture (optional)')
  713. upload_img = gr.File(type='binary')
  714. buttons["Upload character"] = gr.Button(value="Submit")
  715. with gr.Tab('Upload your profile picture'):
  716. upload_img_me = gr.File(type='binary')
  717. with gr.Tab('Upload TavernAI Character Card'):
  718. upload_img_tavern = gr.File(type='binary')
  719. if args.extensions is not None:
  720. create_extensions_block()
  721. input_params = [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check, history_size_slider]
  722. if args.cai_chat:
  723. gen_events.append(buttons["Generate"].click(cai_chatbot_wrapper, input_params, display, show_progress=args.no_stream, api_name="textgen"))
  724. gen_events.append(textbox.submit(cai_chatbot_wrapper, input_params, display, show_progress=args.no_stream))
  725. else:
  726. gen_events.append(buttons["Generate"].click(chatbot_wrapper, input_params, display, show_progress=args.no_stream, api_name="textgen"))
  727. gen_events.append(textbox.submit(chatbot_wrapper, input_params, display, show_progress=args.no_stream))
  728. gen_events.append(buttons["Regenerate"].click(regenerate_wrapper, input_params, display, show_progress=args.no_stream))
  729. gen_events.append(buttons["Impersonate"].click(impersonate_wrapper, input_params, textbox, show_progress=args.no_stream))
  730. buttons["Send last reply to input"].click(send_last_reply_to_input, [], textbox, show_progress=args.no_stream)
  731. buttons["Replace last reply"].click(replace_last_reply, [textbox, name1, name2], display, show_progress=args.no_stream)
  732. buttons["Clear"].click(clear_chat_log, [character_menu, name1, name2], display)
  733. buttons["Remove last"].click(remove_last_message, [name1, name2], [display, textbox], show_progress=False)
  734. buttons["Stop"].click(None, None, None, cancels=gen_events)
  735. buttons["Download"].click(save_history, inputs=[], outputs=[download])
  736. buttons["Upload character"].click(upload_character, [upload_char, upload_img], [character_menu])
  737. for i in ["Generate", "Regenerate", "Replace last reply"]:
  738. buttons[i].click(lambda x: "", textbox, textbox, show_progress=False)
  739. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  740. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display])
  741. upload_img_tavern.upload(upload_tavern_character, [upload_img_tavern, name1, name2], [character_menu])
  742. upload.upload(upload_history, [upload, name1, name2], [])
  743. upload_img_me.upload(upload_your_profile_picture, [upload_img_me], [])
  744. if args.cai_chat:
  745. upload.upload(redraw_html, [name1, name2], [display])
  746. upload_img_me.upload(redraw_html, [name1, name2], [display])
  747. else:
  748. upload.upload(lambda : history['visible'], [], [display])
  749. upload_img_me.upload(lambda : history['visible'], [], [display])
  750. elif args.notebook:
  751. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  752. gr.Markdown(description)
  753. with gr.Tab('Raw'):
  754. textbox = gr.Textbox(value=default_text, lines=23)
  755. with gr.Tab('Markdown'):
  756. markdown = gr.Markdown()
  757. with gr.Tab('HTML'):
  758. html = gr.HTML()
  759. buttons["Generate"] = gr.Button("Generate")
  760. buttons["Stop"] = gr.Button("Stop")
  761. 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'])
  762. with gr.Row():
  763. with gr.Column():
  764. with gr.Row():
  765. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  766. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  767. with gr.Column():
  768. with gr.Row():
  769. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Generation parameters preset')
  770. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  771. if args.extensions is not None:
  772. create_extensions_block()
  773. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  774. gen_events.append(textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream))
  775. buttons["Stop"].click(None, None, None, cancels=gen_events)
  776. else:
  777. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  778. gr.Markdown(description)
  779. with gr.Row():
  780. with gr.Column():
  781. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  782. 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'])
  783. with gr.Row():
  784. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Generation parameters preset')
  785. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  786. with gr.Row():
  787. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  788. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  789. buttons["Generate"] = gr.Button("Generate")
  790. with gr.Row():
  791. with gr.Column():
  792. buttons["Continue"] = gr.Button("Continue")
  793. with gr.Column():
  794. buttons["Stop"] = gr.Button("Stop")
  795. if args.extensions is not None:
  796. create_extensions_block()
  797. with gr.Column():
  798. with gr.Tab('Raw'):
  799. output_textbox = gr.Textbox(lines=15, label='Output')
  800. with gr.Tab('Markdown'):
  801. markdown = gr.Markdown()
  802. with gr.Tab('HTML'):
  803. html = gr.HTML()
  804. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  805. gen_events.append(textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream))
  806. gen_events.append(buttons["Continue"].click(generate_reply, [output_textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream))
  807. buttons["Stop"].click(None, None, None, cancels=gen_events)
  808. interface.queue()
  809. if args.listen:
  810. interface.launch(share=args.share, server_name="0.0.0.0", server_port=args.listen_port)
  811. else:
  812. interface.launch(share=args.share, server_port=args.listen_port)