server.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. import argparse
  2. import base64
  3. import copy
  4. import gc
  5. import glob
  6. import io
  7. import json
  8. import os
  9. import re
  10. import sys
  11. import time
  12. import warnings
  13. import zipfile
  14. from datetime import datetime
  15. from pathlib import Path
  16. import gradio as gr
  17. import numpy as np
  18. import torch
  19. import transformers
  20. from PIL import Image
  21. from tqdm import tqdm
  22. from transformers import AutoConfig
  23. from transformers import AutoModelForCausalLM
  24. from transformers import AutoTokenizer
  25. from io import BytesIO
  26. from modules.html_generator import *
  27. from modules.stopping_criteria import _SentinelTokenStoppingCriteria
  28. from modules.ui import *
  29. transformers.logging.set_verbosity_error()
  30. parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54))
  31. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  32. 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.')
  33. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  34. 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.')
  35. parser.add_argument('--picture', action='store_true', help='Adds an ability to send pictures in chat UI modes. Captions are generated by BLIP.')
  36. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  37. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  38. parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.')
  39. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  40. 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.')
  41. parser.add_argument('--disk-cache-dir', type=str, help='Directory to save the disk cache to. Defaults to "cache/".')
  42. 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.')
  43. 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.')
  44. parser.add_argument('--flexgen', action='store_true', help='Enable the use of FlexGen offloading.')
  45. parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.')
  46. parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.')
  47. parser.add_argument('--local_rank', type=int, default=0, help='DeepSpeed: Optional argument for distributed setups.')
  48. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This improves the text generation performance.')
  49. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  50. 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".')
  51. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  52. parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
  53. 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.')
  54. parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.')
  55. args = parser.parse_args()
  56. if (args.chat or args.cai_chat) and not args.no_stream:
  57. print("Warning: chat mode currently becomes somewhat slower with text streaming on.\nConsider starting the web UI with the --no-stream option.\n")
  58. settings = {
  59. 'max_new_tokens': 200,
  60. 'max_new_tokens_min': 1,
  61. 'max_new_tokens_max': 2000,
  62. 'preset': 'NovelAI-Sphinx Moth',
  63. 'name1': 'Person 1',
  64. 'name2': 'Person 2',
  65. 'context': 'This is a conversation between two people.',
  66. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  67. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  68. 'stop_at_newline': True,
  69. 'chat_prompt_size': 2048,
  70. 'chat_prompt_size_min': 0,
  71. 'chat_prompt_size_max': 2048,
  72. 'preset_pygmalion': 'Pygmalion',
  73. 'name1_pygmalion': 'You',
  74. 'name2_pygmalion': 'Kawaii',
  75. '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>",
  76. 'stop_at_newline_pygmalion': False,
  77. }
  78. if args.settings is not None and Path(args.settings).exists():
  79. new_settings = json.loads(open(Path(args.settings), 'r').read())
  80. for item in new_settings:
  81. settings[item] = new_settings[item]
  82. if args.flexgen:
  83. from flexgen.flex_opt import (Policy, OptLM, TorchDevice, TorchDisk, TorchMixedDevice, CompressionConfig, Env, Task, get_opt_config)
  84. if args.deepspeed:
  85. import deepspeed
  86. from transformers.deepspeed import HfDeepSpeedConfig, is_deepspeed_zero3_enabled
  87. from modules.deepspeed_parameters import generate_ds_config
  88. # Distributed setup
  89. local_rank = args.local_rank if args.local_rank is not None else int(os.getenv("LOCAL_RANK", "0"))
  90. world_size = int(os.getenv("WORLD_SIZE", "1"))
  91. torch.cuda.set_device(local_rank)
  92. deepspeed.init_distributed()
  93. ds_config = generate_ds_config(args.bf16, 1 * world_size, args.nvme_offload_dir)
  94. dschf = HfDeepSpeedConfig(ds_config) # Keep this object alive for the Transformers integration
  95. if args.picture and (args.cai_chat or args.chat):
  96. import modules.bot_picture as bot_picture
  97. def load_model(model_name):
  98. print(f"Loading {model_name}...")
  99. t0 = time.time()
  100. # Default settings
  101. 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 or args.flexgen):
  102. if any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  103. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  104. else:
  105. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.bfloat16 if args.bf16 else torch.float16).cuda()
  106. # FlexGen
  107. elif args.flexgen:
  108. gpu = TorchDevice("cuda:0")
  109. cpu = TorchDevice("cpu")
  110. disk = TorchDisk("cache")
  111. env = Env(gpu=gpu, cpu=cpu, disk=disk, mixed=TorchMixedDevice([gpu, cpu, disk]))
  112. # Offloading policy
  113. policy = Policy(1, 1,
  114. 100, 0,
  115. 100, 0,
  116. 100, 0,
  117. overlap=True, sep_layer=True, pin_weight=True,
  118. cpu_cache_compute=False, attn_sparsity=1.0,
  119. compress_weight=False,
  120. comp_weight_config=CompressionConfig(
  121. num_bits=4, group_size=64,
  122. group_dim=0, symmetric=False),
  123. compress_cache=False,
  124. comp_cache_config=CompressionConfig(
  125. num_bits=4, group_size=64,
  126. group_dim=2, symmetric=False))
  127. opt_config = get_opt_config(f"facebook/{model_name}")
  128. model = OptLM(opt_config, env, "models", policy)
  129. model.init_all_weights()
  130. # DeepSpeed ZeRO-3
  131. elif args.deepspeed:
  132. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), torch_dtype=torch.bfloat16 if args.bf16 else torch.float16)
  133. model = deepspeed.initialize(model=model, config_params=ds_config, model_parameters=None, optimizer=None, lr_scheduler=None)[0]
  134. model.module.eval() # Inference
  135. print(f"DeepSpeed ZeRO-3 is enabled: {is_deepspeed_zero3_enabled()}")
  136. # Custom
  137. else:
  138. command = "AutoModelForCausalLM.from_pretrained"
  139. params = ["low_cpu_mem_usage=True"]
  140. if not args.cpu and not torch.cuda.is_available():
  141. print("Warning: no GPU has been detected.\nFalling back to CPU mode.\n")
  142. args.cpu = True
  143. if args.cpu:
  144. params.append("low_cpu_mem_usage=True")
  145. params.append("torch_dtype=torch.float32")
  146. else:
  147. params.append("device_map='auto'")
  148. params.append("load_in_8bit=True" if args.load_in_8bit else "torch_dtype=torch.bfloat16" if args.bf16 else "torch_dtype=torch.float16")
  149. if args.gpu_memory:
  150. params.append(f"max_memory={{0: '{args.gpu_memory or '99'}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  151. elif not args.load_in_8bit:
  152. total_mem = (torch.cuda.get_device_properties(0).total_memory/(1024*1024))
  153. suggestion = round((total_mem-1000)/1000)*1000
  154. if total_mem-suggestion < 800:
  155. suggestion -= 1000
  156. suggestion = int(round(suggestion/1000))
  157. 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")
  158. params.append(f"max_memory={{0: '{suggestion}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  159. if args.disk:
  160. params.append(f"offload_folder='{args.disk_cache_dir or 'cache'}'")
  161. command = f"{command}(Path(f'models/{model_name}'), {', '.join(set(params))})"
  162. model = eval(command)
  163. # Loading the tokenizer
  164. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  165. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  166. else:
  167. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  168. tokenizer.truncation_side = 'left'
  169. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  170. return model, tokenizer
  171. def load_soft_prompt(name):
  172. global soft_prompt, soft_prompt_tensor
  173. if name == 'None':
  174. soft_prompt = False
  175. soft_prompt_tensor = None
  176. else:
  177. with zipfile.ZipFile(Path(f'softprompts/{name}.zip')) as zf:
  178. zf.extract('tensor.npy')
  179. zf.extract('meta.json')
  180. j = json.loads(open('meta.json', 'r').read())
  181. print(f"\nLoading the softprompt \"{name}\".")
  182. for field in j:
  183. if field != 'name':
  184. if type(j[field]) is list:
  185. print(f"{field}: {', '.join(j[field])}")
  186. else:
  187. print(f"{field}: {j[field]}")
  188. print()
  189. tensor = np.load('tensor.npy')
  190. Path('tensor.npy').unlink()
  191. Path('meta.json').unlink()
  192. tensor = torch.Tensor(tensor).to(device=model.device, dtype=model.dtype)
  193. tensor = torch.reshape(tensor, (1, tensor.shape[0], tensor.shape[1]))
  194. soft_prompt = True
  195. soft_prompt_tensor = tensor
  196. return name
  197. def upload_soft_prompt(file):
  198. with zipfile.ZipFile(io.BytesIO(file)) as zf:
  199. zf.extract('meta.json')
  200. j = json.loads(open('meta.json', 'r').read())
  201. name = j['name']
  202. Path('meta.json').unlink()
  203. with open(Path(f'softprompts/{name}.zip'), 'wb') as f:
  204. f.write(file)
  205. return name
  206. def load_model_wrapper(selected_model):
  207. global model_name, model, tokenizer
  208. if selected_model != model_name:
  209. model_name = selected_model
  210. model = tokenizer = None
  211. if not args.cpu:
  212. gc.collect()
  213. torch.cuda.empty_cache()
  214. model, tokenizer = load_model(model_name)
  215. return selected_model
  216. def load_preset_values(preset_menu, return_dict=False):
  217. generate_params = {
  218. 'do_sample': True,
  219. 'temperature': 1,
  220. 'top_p': 1,
  221. 'typical_p': 1,
  222. 'repetition_penalty': 1,
  223. 'top_k': 50,
  224. 'num_beams': 1,
  225. 'penalty_alpha': 0,
  226. 'min_length': 0,
  227. 'length_penalty': 1,
  228. 'no_repeat_ngram_size': 0,
  229. 'early_stopping': False,
  230. }
  231. with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
  232. preset = infile.read()
  233. for i in preset.splitlines():
  234. i = i.rstrip(',').strip().split('=')
  235. if len(i) == 2 and i[0].strip() != 'tokens':
  236. generate_params[i[0].strip()] = eval(i[1].strip())
  237. generate_params['temperature'] = min(1.99, generate_params['temperature'])
  238. if return_dict:
  239. return generate_params
  240. else:
  241. return generate_params['do_sample'], generate_params['temperature'], generate_params['top_p'], generate_params['typical_p'], generate_params['repetition_penalty'], generate_params['top_k'], generate_params['min_length'], generate_params['no_repeat_ngram_size'], generate_params['num_beams'], generate_params['penalty_alpha'], generate_params['length_penalty'], generate_params['early_stopping']
  242. # Removes empty replies from gpt4chan outputs
  243. def fix_gpt4chan(s):
  244. for i in range(10):
  245. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  246. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  247. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  248. return s
  249. # Fix the LaTeX equations in galactica
  250. def fix_galactica(s):
  251. s = s.replace(r'\[', r'$')
  252. s = s.replace(r'\]', r'$')
  253. s = s.replace(r'\(', r'$')
  254. s = s.replace(r'\)', r'$')
  255. s = s.replace(r'$$', r'$')
  256. s = re.sub(r'\n', r'\n\n', s)
  257. s = re.sub(r"\n{3,}", "\n\n", s)
  258. return s
  259. def get_max_prompt_length(tokens):
  260. global soft_prompt, soft_prompt_tensor
  261. max_length = 2048-tokens
  262. if soft_prompt:
  263. max_length -= soft_prompt_tensor.shape[1]
  264. return max_length
  265. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  266. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=get_max_prompt_length(tokens_to_generate), add_special_tokens=add_special_tokens)
  267. if args.cpu or args.flexgen:
  268. return input_ids
  269. elif args.deepspeed:
  270. return input_ids.to(device=local_rank)
  271. else:
  272. return input_ids.cuda()
  273. def decode(output_ids):
  274. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  275. reply = reply.replace(r'<|endoftext|>', '')
  276. return reply
  277. def formatted_outputs(reply, model_name):
  278. if not (args.chat or args.cai_chat):
  279. if model_name.lower().startswith('galactica'):
  280. reply = fix_galactica(reply)
  281. return reply, reply, generate_basic_html(reply)
  282. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  283. reply = fix_gpt4chan(reply)
  284. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  285. else:
  286. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  287. else:
  288. return reply
  289. def generate_softprompt_input_tensors(input_ids):
  290. inputs_embeds = model.transformer.wte(input_ids)
  291. inputs_embeds = torch.cat((soft_prompt_tensor, inputs_embeds), dim=1)
  292. filler_input_ids = torch.zeros((1, inputs_embeds.shape[1]), dtype=input_ids.dtype).to(model.device)
  293. filler_input_ids += model.config.bos_token_id # setting dummy input_ids to bos tokens
  294. return inputs_embeds, filler_input_ids
  295. def generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=None, stopping_string=None):
  296. global model_name, model, tokenizer, soft_prompt, soft_prompt_tensor
  297. original_question = question
  298. if not (args.chat or args.cai_chat):
  299. question = apply_extensions(question, "input")
  300. if args.verbose:
  301. print(f"\n\n{question}\n--------------------\n")
  302. input_ids = encode(question, tokens)
  303. cuda = "" if (args.cpu or args.deepspeed or args.flexgen) else ".cuda()"
  304. n = tokenizer.eos_token_id if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  305. if stopping_string is not None:
  306. # The stopping_criteria code below was copied from
  307. # https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py
  308. t = encode(stopping_string, 0, add_special_tokens=False)
  309. stopping_criteria_list = transformers.StoppingCriteriaList([
  310. _SentinelTokenStoppingCriteria(
  311. sentinel_token_ids=t,
  312. starting_idx=len(input_ids[0])
  313. )
  314. ])
  315. else:
  316. stopping_criteria_list = None
  317. if not args.flexgen:
  318. generate_params = [
  319. f"eos_token_id={n}",
  320. f"stopping_criteria=stopping_criteria_list",
  321. f"do_sample={do_sample}",
  322. f"temperature={temperature}",
  323. f"top_p={top_p}",
  324. f"typical_p={typical_p}",
  325. f"repetition_penalty={repetition_penalty}",
  326. f"top_k={top_k}",
  327. f"min_length={min_length if args.no_stream else 0}",
  328. f"no_repeat_ngram_size={no_repeat_ngram_size}",
  329. f"num_beams={num_beams}",
  330. f"penalty_alpha={penalty_alpha}",
  331. f"length_penalty={length_penalty}",
  332. f"early_stopping={early_stopping}",
  333. ]
  334. else:
  335. generate_params = [
  336. f"do_sample={do_sample}",
  337. f"temperature={temperature}",
  338. ]
  339. if args.deepspeed:
  340. generate_params.append("synced_gpus=True")
  341. if args.no_stream:
  342. generate_params.append(f"max_new_tokens=tokens")
  343. else:
  344. generate_params.append(f"max_new_tokens=8")
  345. if soft_prompt:
  346. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  347. generate_params.insert(0, "inputs_embeds=inputs_embeds")
  348. generate_params.insert(0, "filler_input_ids")
  349. else:
  350. generate_params.insert(0, "input_ids")
  351. # Generate the entire reply at once
  352. if args.no_stream:
  353. t0 = time.time()
  354. with torch.no_grad():
  355. output = eval(f"model.generate({', '.join(generate_params)}){cuda}")[0]
  356. if soft_prompt:
  357. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  358. reply = decode(output)
  359. if not (args.chat or args.cai_chat):
  360. reply = original_question + apply_extensions(reply[len(question):], "output")
  361. yield formatted_outputs(reply, model_name)
  362. t1 = time.time()
  363. print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output)-len(input_ids[0]))/(t1-t0)/8:.2f} it/s, {len(output)-len(input_ids[0])} tokens)")
  364. # Generate the reply 8 tokens at a time
  365. else:
  366. yield formatted_outputs(original_question, model_name)
  367. for i in tqdm(range(tokens//8+1)):
  368. with torch.no_grad():
  369. output = eval(f"model.generate({', '.join(generate_params)}){cuda}")[0]
  370. if soft_prompt:
  371. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  372. reply = decode(output)
  373. if not (args.chat or args.cai_chat):
  374. reply = original_question + apply_extensions(reply[len(question):], "output")
  375. yield formatted_outputs(reply, model_name)
  376. if not args.flexgen:
  377. input_ids = torch.reshape(output, (1, output.shape[0]))
  378. else:
  379. input_ids = np.reshape(output, (1, output.shape[0]))
  380. if soft_prompt:
  381. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  382. if output[-1] == n:
  383. break
  384. def apply_extensions(text, typ):
  385. global available_extensions, extension_state
  386. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  387. if extension_state[ext][0] == True:
  388. ext_string = f"extensions.{ext}.script"
  389. if typ == "input" and hasattr(eval(ext_string), "input_modifier"):
  390. text = eval(f"{ext_string}.input_modifier(text)")
  391. elif typ == "output" and hasattr(eval(ext_string), "output_modifier"):
  392. text = eval(f"{ext_string}.output_modifier(text)")
  393. elif typ == "bot_prefix" and hasattr(eval(ext_string), "bot_prefix_modifier"):
  394. text = eval(f"{ext_string}.bot_prefix_modifier(text)")
  395. return text
  396. def update_extensions_parameters(*kwargs):
  397. i = 0
  398. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  399. if extension_state[ext][0] == True:
  400. params = eval(f"extensions.{ext}.script.params")
  401. for param in params:
  402. if len(kwargs) >= i+1:
  403. params[param] = eval(f"kwargs[{i}]")
  404. i += 1
  405. def get_available_models():
  406. return sorted([item.name for item in list(Path('models/').glob('*')) if not item.name.endswith('.txt')], key=str.lower)
  407. def get_available_presets():
  408. return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  409. def get_available_characters():
  410. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  411. def get_available_extensions():
  412. return sorted(set(map(lambda x : x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
  413. def get_available_softprompts():
  414. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('softprompts').glob('*.zip'))), key=str.lower)
  415. def create_extensions_block():
  416. extensions_ui_elements = []
  417. default_values = []
  418. if not (args.chat or args.cai_chat):
  419. gr.Markdown('## Extensions parameters')
  420. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  421. if extension_state[ext][0] == True:
  422. params = eval(f"extensions.{ext}.script.params")
  423. for param in params:
  424. _id = f"{ext}-{param}"
  425. default_value = settings[_id] if _id in settings else params[param]
  426. default_values.append(default_value)
  427. if type(params[param]) == str:
  428. extensions_ui_elements.append(gr.Textbox(value=default_value, label=f"{ext}-{param}"))
  429. elif type(params[param]) in [int, float]:
  430. extensions_ui_elements.append(gr.Number(value=default_value, label=f"{ext}-{param}"))
  431. elif type(params[param]) == bool:
  432. extensions_ui_elements.append(gr.Checkbox(value=default_value, label=f"{ext}-{param}"))
  433. update_extensions_parameters(*default_values)
  434. btn_extensions = gr.Button("Apply")
  435. btn_extensions.click(update_extensions_parameters, [*extensions_ui_elements], [])
  436. def create_settings_menus():
  437. generate_params = load_preset_values(settings[f'preset{suffix}'], return_dict=True)
  438. with gr.Row():
  439. with gr.Column():
  440. with gr.Row():
  441. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  442. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  443. with gr.Column():
  444. with gr.Row():
  445. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Generation parameters preset')
  446. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  447. with gr.Accordion("Custom generation parameters", open=False, elem_id="accordion"):
  448. with gr.Row():
  449. do_sample = gr.Checkbox(value=generate_params['do_sample'], label="do_sample")
  450. temperature = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label="temperature")
  451. with gr.Row():
  452. top_k = gr.Slider(0,200,value=generate_params['top_k'],step=1,label="top_k")
  453. top_p = gr.Slider(0.0,1.0,value=generate_params['top_p'],step=0.01,label="top_p")
  454. with gr.Row():
  455. repetition_penalty = gr.Slider(1.0,4.99,value=generate_params['repetition_penalty'],step=0.01,label="repetition_penalty")
  456. no_repeat_ngram_size = gr.Slider(0, 20, step=1, value=generate_params["no_repeat_ngram_size"], label="no_repeat_ngram_size")
  457. with gr.Row():
  458. typical_p = gr.Slider(0.0,1.0,value=generate_params['typical_p'],step=0.01,label="typical_p")
  459. min_length = gr.Slider(0, 2000, step=1, value=generate_params["min_length"] if args.no_stream else 0, label="min_length", interactive=args.no_stream)
  460. gr.Markdown("Contrastive search:")
  461. penalty_alpha = gr.Slider(0, 5, value=generate_params["penalty_alpha"], label="penalty_alpha")
  462. gr.Markdown("Beam search (uses a lot of VRAM):")
  463. with gr.Row():
  464. num_beams = gr.Slider(1, 20, step=1, value=generate_params["num_beams"], label="num_beams")
  465. length_penalty = gr.Slider(-5, 5, value=generate_params["length_penalty"], label="length_penalty")
  466. early_stopping = gr.Checkbox(value=generate_params["early_stopping"], label="early_stopping")
  467. with gr.Accordion("Soft prompt", open=False, elem_id="accordion"):
  468. with gr.Row():
  469. softprompts_menu = gr.Dropdown(choices=available_softprompts, value="None", label='Soft prompt')
  470. create_refresh_button(softprompts_menu, lambda : None, lambda : {"choices": get_available_softprompts()}, "refresh-button")
  471. gr.Markdown('Upload a soft prompt (.zip format):')
  472. with gr.Row():
  473. upload_softprompt = gr.File(type='binary', file_types=[".zip"])
  474. model_menu.change(load_model_wrapper, [model_menu], [model_menu], show_progress=True)
  475. preset_menu.change(load_preset_values, [preset_menu], [do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping])
  476. softprompts_menu.change(load_soft_prompt, [softprompts_menu], [softprompts_menu], show_progress=True)
  477. upload_softprompt.upload(upload_soft_prompt, [upload_softprompt], [softprompts_menu])
  478. return preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping
  479. # This gets the new line characters right.
  480. def clean_chat_message(text):
  481. text = text.replace('\n', '\n\n')
  482. text = re.sub(r"\n{3,}", "\n\n", text)
  483. text = text.strip()
  484. return text
  485. def generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size, impersonate=False):
  486. global soft_prompt, soft_prompt_tensor
  487. text = clean_chat_message(text)
  488. rows = [f"{context.strip()}\n"]
  489. i = len(history['internal'])-1
  490. count = 0
  491. if soft_prompt:
  492. chat_prompt_size -= soft_prompt_tensor.shape[1]
  493. max_length = min(get_max_prompt_length(tokens), chat_prompt_size)
  494. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < max_length:
  495. rows.insert(1, f"{name2}: {history['internal'][i][1].strip()}\n")
  496. count += 1
  497. if not (history['internal'][i][0] == '<|BEGIN-VISIBLE-CHAT|>'):
  498. rows.insert(1, f"{name1}: {history['internal'][i][0].strip()}\n")
  499. count += 1
  500. i -= 1
  501. if not impersonate:
  502. rows.append(f"{name1}: {text}\n")
  503. rows.append(apply_extensions(f"{name2}:", "bot_prefix"))
  504. limit = 3
  505. else:
  506. rows.append(f"{name1}:")
  507. limit = 2
  508. while len(rows) > limit and len(encode(''.join(rows), tokens)[0]) >= max_length:
  509. rows.pop(1)
  510. rows.pop(1)
  511. question = ''.join(rows)
  512. return question
  513. def extract_message_from_reply(question, reply, current, other, check, extensions=False):
  514. next_character_found = False
  515. substring_found = False
  516. previous_idx = [m.start() for m in re.finditer(f"(^|\n){re.escape(current)}:", question)]
  517. idx = [m.start() for m in re.finditer(f"(^|\n){re.escape(current)}:", reply)]
  518. idx = idx[len(previous_idx)-1]
  519. if extensions:
  520. reply = reply[idx + 1 + len(apply_extensions(f"{current}:", "bot_prefix")):]
  521. else:
  522. reply = reply[idx + 1 + len(f"{current}:"):]
  523. if check:
  524. reply = reply.split('\n')[0].strip()
  525. else:
  526. idx = reply.find(f"\n{other}:")
  527. if idx != -1:
  528. reply = reply[:idx]
  529. next_character_found = True
  530. reply = clean_chat_message(reply)
  531. # Detect if something like "\nYo" is generated just before
  532. # "\nYou:" is completed
  533. tmp = f"\n{other}:"
  534. for j in range(1, len(tmp)):
  535. if reply[-j:] == tmp[:j]:
  536. substring_found = True
  537. return reply, next_character_found, substring_found
  538. def generate_chat_picture(picture, name1, name2):
  539. text = f'*{name1} sends {name2} a picture that contains the following: "{bot_picture.caption_image(picture)}"*'
  540. buffer = BytesIO()
  541. picture.save(buffer, format="JPEG")
  542. img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
  543. visible_text = f'<img src="data:image/jpeg;base64,{img_str}">'
  544. return text, visible_text
  545. def stop_everything_event():
  546. global stop_everything
  547. stop_everything = True
  548. def chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  549. global stop_everything
  550. stop_everything = False
  551. if 'pygmalion' in model_name.lower():
  552. name1 = "You"
  553. if args.picture and picture is not None:
  554. text, visible_text = generate_chat_picture(picture, name1, name2)
  555. else:
  556. visible_text = text
  557. if args.chat:
  558. visible_text = visible_text.replace('\n', '<br>')
  559. text = apply_extensions(text, "input")
  560. question = generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size)
  561. eos_token = '\n' if check else None
  562. first = True
  563. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name1}:"):
  564. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name2, name1, check, extensions=True)
  565. visible_reply = apply_extensions(reply, "output")
  566. if args.chat:
  567. visible_reply = visible_reply.replace('\n', '<br>')
  568. # We need this global variable to handle the Stop event,
  569. # otherwise gradio gets confused
  570. if stop_everything:
  571. return history['visible']
  572. if first:
  573. first = False
  574. history['internal'].append(['', ''])
  575. history['visible'].append(['', ''])
  576. history['internal'][-1] = [text, reply]
  577. history['visible'][-1] = [visible_text, visible_reply]
  578. if not substring_found:
  579. yield history['visible']
  580. if next_character_found:
  581. break
  582. yield history['visible']
  583. def impersonate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  584. if 'pygmalion' in model_name.lower():
  585. name1 = "You"
  586. question = generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size, impersonate=True)
  587. eos_token = '\n' if check else None
  588. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name2}:"):
  589. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name1, name2, check, extensions=False)
  590. if not substring_found:
  591. yield reply
  592. if next_character_found:
  593. break
  594. yield reply
  595. def cai_chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  596. for _history in chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture):
  597. yield generate_chat_html(_history, name1, name2, character)
  598. def regenerate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  599. if character is not None and len(history['visible']) == 1:
  600. if args.cai_chat:
  601. yield generate_chat_html(history['visible'], name1, name2, character)
  602. else:
  603. yield history['visible']
  604. else:
  605. last_visible = history['visible'].pop()
  606. last_internal = history['internal'].pop()
  607. for _history in chatbot_wrapper(last_internal[0], tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture):
  608. if args.cai_chat:
  609. history['visible'][-1] = [last_visible[0], _history[-1][1]]
  610. yield generate_chat_html(history['visible'], name1, name2, character)
  611. else:
  612. history['visible'][-1] = (last_visible[0], _history[-1][1])
  613. yield history['visible']
  614. def remove_last_message(name1, name2):
  615. if not history['internal'][-1][0] == '<|BEGIN-VISIBLE-CHAT|>':
  616. last = history['visible'].pop()
  617. history['internal'].pop()
  618. else:
  619. last = ['', '']
  620. if args.cai_chat:
  621. return generate_chat_html(history['visible'], name1, name2, character), last[0]
  622. else:
  623. return history['visible'], last[0]
  624. def send_last_reply_to_input():
  625. if len(history['internal']) > 0:
  626. return history['internal'][-1][1]
  627. else:
  628. return ''
  629. def replace_last_reply(text, name1, name2):
  630. if len(history['visible']) > 0:
  631. if args.cai_chat:
  632. history['visible'][-1][1] = text
  633. else:
  634. history['visible'][-1] = (history['visible'][-1][0], text)
  635. history['internal'][-1][1] = apply_extensions(text, "input")
  636. if args.cai_chat:
  637. return generate_chat_html(history['visible'], name1, name2, character)
  638. else:
  639. return history['visible']
  640. def clear_html():
  641. return generate_chat_html([], "", "", character)
  642. def clear_chat_log(_character, name1, name2):
  643. global history
  644. if _character != 'None':
  645. for i in range(len(history['internal'])):
  646. if '<|BEGIN-VISIBLE-CHAT|>' in history['internal'][i][0]:
  647. history['visible'] = [['', history['internal'][i][1]]]
  648. history['internal'] = history['internal'][:i+1]
  649. break
  650. else:
  651. history['internal'] = []
  652. history['visible'] = []
  653. if args.cai_chat:
  654. return generate_chat_html(history['visible'], name1, name2, character)
  655. else:
  656. return history['visible']
  657. def redraw_html(name1, name2):
  658. global history
  659. return generate_chat_html(history['visible'], name1, name2, character)
  660. def tokenize_dialogue(dialogue, name1, name2):
  661. _history = []
  662. dialogue = re.sub('<START>', '', dialogue)
  663. dialogue = re.sub('<start>', '', dialogue)
  664. dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue)
  665. dialogue = re.sub('(\n|^)\[CHARACTER\]:', f'\\g<1>{name2}:', dialogue)
  666. idx = [m.start() for m in re.finditer(f"(^|\n)({re.escape(name1)}|{re.escape(name2)}):", dialogue)]
  667. if len(idx) == 0:
  668. return _history
  669. messages = []
  670. for i in range(len(idx)-1):
  671. messages.append(dialogue[idx[i]:idx[i+1]].strip())
  672. messages.append(dialogue[idx[-1]:].strip())
  673. entry = ['', '']
  674. for i in messages:
  675. if i.startswith(f'{name1}:'):
  676. entry[0] = i[len(f'{name1}:'):].strip()
  677. elif i.startswith(f'{name2}:'):
  678. entry[1] = i[len(f'{name2}:'):].strip()
  679. if not (len(entry[0]) == 0 and len(entry[1]) == 0):
  680. _history.append(entry)
  681. entry = ['', '']
  682. print(f"\033[1;32;1m\nDialogue tokenized to:\033[0;37;0m\n", end='')
  683. for row in _history:
  684. for column in row:
  685. print("\n")
  686. for line in column.strip().split('\n'):
  687. print("| "+line+"\n")
  688. print("|\n")
  689. print("------------------------------")
  690. return _history
  691. def save_history(timestamp=True):
  692. if timestamp:
  693. fname = f"{character or ''}{'_' if character else ''}{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  694. else:
  695. fname = f"{character or ''}{'_' if character else ''}persistent.json"
  696. if not Path('logs').exists():
  697. Path('logs').mkdir()
  698. with open(Path(f'logs/{fname}'), 'w') as f:
  699. f.write(json.dumps({'data': history['internal'], 'data_visible': history['visible']}, indent=2))
  700. return Path(f'logs/{fname}')
  701. def load_history(file, name1, name2):
  702. global history
  703. file = file.decode('utf-8')
  704. try:
  705. j = json.loads(file)
  706. if 'data' in j:
  707. history['internal'] = j['data']
  708. if 'data_visible' in j:
  709. history['visible'] = j['data_visible']
  710. else:
  711. history['visible'] = copy.deepcopy(history['internal'])
  712. # Compatibility with Pygmalion AI's official web UI
  713. elif 'chat' in j:
  714. history['internal'] = [':'.join(x.split(':')[1:]).strip() for x in j['chat']]
  715. if len(j['chat']) > 0 and j['chat'][0].startswith(f'{name2}:'):
  716. 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)]
  717. history['visible'] = copy.deepcopy(history['internal'])
  718. history['visible'][0][0] = ''
  719. else:
  720. history['internal'] = [[history['internal'][i], history['internal'][i+1]] for i in range(0, len(history['internal'])-1, 2)]
  721. history['visible'] = copy.deepcopy(history['internal'])
  722. except:
  723. history['internal'] = tokenize_dialogue(file, name1, name2)
  724. history['visible'] = copy.deepcopy(history['internal'])
  725. def load_character(_character, name1, name2):
  726. global history, character
  727. context = ""
  728. history['internal'] = []
  729. history['visible'] = []
  730. if _character != 'None':
  731. character = _character
  732. data = json.loads(open(Path(f'characters/{_character}.json'), 'r').read())
  733. name2 = data['char_name']
  734. if 'char_persona' in data and data['char_persona'] != '':
  735. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  736. if 'world_scenario' in data and data['world_scenario'] != '':
  737. context += f"Scenario: {data['world_scenario']}\n"
  738. context = f"{context.strip()}\n<START>\n"
  739. if 'example_dialogue' in data and data['example_dialogue'] != '':
  740. history['internal'] = tokenize_dialogue(data['example_dialogue'], name1, name2)
  741. if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0:
  742. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]]
  743. history['visible'] += [['', apply_extensions(data['char_greeting'], "output")]]
  744. else:
  745. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]]
  746. history['visible'] += [['', "Hello there!"]]
  747. else:
  748. character = None
  749. context = settings['context_pygmalion']
  750. name2 = settings['name2_pygmalion']
  751. if Path(f'logs/{character}_persistent.json').exists():
  752. load_history(open(Path(f'logs/{character}_persistent.json'), 'rb').read(), name1, name2)
  753. if args.cai_chat:
  754. return name2, context, generate_chat_html(history['visible'], name1, name2, character)
  755. else:
  756. return name2, context, history['visible']
  757. def upload_character(json_file, img, tavern=False):
  758. json_file = json_file if type(json_file) == str else json_file.decode('utf-8')
  759. data = json.loads(json_file)
  760. outfile_name = data["char_name"]
  761. i = 1
  762. while Path(f'characters/{outfile_name}.json').exists():
  763. outfile_name = f'{data["char_name"]}_{i:03d}'
  764. i += 1
  765. if tavern:
  766. outfile_name = f'TavernAI-{outfile_name}'
  767. with open(Path(f'characters/{outfile_name}.json'), 'w') as f:
  768. f.write(json_file)
  769. if img is not None:
  770. img = Image.open(io.BytesIO(img))
  771. img.save(Path(f'characters/{outfile_name}.png'))
  772. print(f'New character saved to "characters/{outfile_name}.json".')
  773. return outfile_name
  774. def upload_tavern_character(img, name1, name2):
  775. _img = Image.open(io.BytesIO(img))
  776. _img.getexif()
  777. decoded_string = base64.b64decode(_img.info['chara'])
  778. _json = json.loads(decoded_string)
  779. _json = {"char_name": _json['name'], "char_persona": _json['description'], "char_greeting": _json["first_mes"], "example_dialogue": _json['mes_example'], "world_scenario": _json['scenario']}
  780. _json['example_dialogue'] = _json['example_dialogue'].replace('{{user}}', name1).replace('{{char}}', _json['char_name'])
  781. return upload_character(json.dumps(_json), img, tavern=True)
  782. def upload_your_profile_picture(img):
  783. img = Image.open(io.BytesIO(img))
  784. img.save(Path(f'img_me.png'))
  785. print(f'Profile picture saved to "img_me.png"')
  786. # Global variables
  787. available_models = get_available_models()
  788. available_presets = get_available_presets()
  789. available_characters = get_available_characters()
  790. available_extensions = get_available_extensions()
  791. available_softprompts = get_available_softprompts()
  792. extension_state = {}
  793. if args.extensions is not None:
  794. for i,ext in enumerate(args.extensions.split(',')):
  795. if ext in available_extensions:
  796. print(f'Loading the extension "{ext}"... ', end='')
  797. ext_string = f"extensions.{ext}.script"
  798. exec(f"import {ext_string}")
  799. extension_state[ext] = [True, i]
  800. print(f'Ok.')
  801. # Choosing the default model
  802. if args.model is not None:
  803. model_name = args.model
  804. else:
  805. if len(available_models) == 0:
  806. print("No models are available! Please download at least one.")
  807. sys.exit(0)
  808. elif len(available_models) == 1:
  809. i = 0
  810. else:
  811. print("The following models are available:\n")
  812. for i,model in enumerate(available_models):
  813. print(f"{i+1}. {model}")
  814. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  815. i = int(input())-1
  816. print()
  817. model_name = available_models[i]
  818. model, tokenizer = load_model(model_name)
  819. loaded_preset = None
  820. soft_prompt_tensor = None
  821. soft_prompt = False
  822. stop_everything = False
  823. # UI settings
  824. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  825. default_text = settings['prompt_gpt4chan']
  826. elif re.match('(rosey|chip|joi)_.*_instruct.*', model_name.lower()) is not None:
  827. default_text = 'User: \n'
  828. else:
  829. default_text = settings['prompt']
  830. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  831. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  832. buttons = {}
  833. gen_events = []
  834. history = {'internal': [], 'visible': []}
  835. character = None
  836. if args.chat or args.cai_chat:
  837. if Path(f'logs/persistent.json').exists():
  838. load_history(open(Path(f'logs/persistent.json'), 'rb').read(), settings[f'name1{suffix}'], settings[f'name2{suffix}'])
  839. with gr.Blocks(css=css+chat_css, analytics_enabled=False) as interface:
  840. if args.cai_chat:
  841. display = gr.HTML(value=generate_chat_html(history['visible'], settings[f'name1{suffix}'], settings[f'name2{suffix}'], character))
  842. else:
  843. display = gr.Chatbot(value=history['visible'])
  844. textbox = gr.Textbox(label='Input')
  845. with gr.Row():
  846. buttons["Stop"] = gr.Button("Stop")
  847. buttons["Generate"] = gr.Button("Generate")
  848. buttons["Regenerate"] = gr.Button("Regenerate")
  849. with gr.Row():
  850. buttons["Impersonate"] = gr.Button("Impersonate")
  851. buttons["Remove last"] = gr.Button("Remove last")
  852. buttons["Clear history"] = gr.Button("Clear history")
  853. with gr.Row():
  854. buttons["Send last reply to input"] = gr.Button("Send last reply to input")
  855. buttons["Replace last reply"] = gr.Button("Replace last reply")
  856. if args.picture:
  857. with gr.Row():
  858. picture_select = gr.Image(label="Send a picture", type='pil')
  859. with gr.Tab("Chat settings"):
  860. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  861. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  862. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  863. with gr.Row():
  864. character_menu = gr.Dropdown(choices=available_characters, value="None", label='Character')
  865. create_refresh_button(character_menu, lambda : None, lambda : {"choices": get_available_characters()}, "refresh-button")
  866. with gr.Row():
  867. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  868. with gr.Row():
  869. with gr.Tab('Chat history'):
  870. with gr.Row():
  871. with gr.Column():
  872. gr.Markdown('Upload')
  873. upload_chat_history = gr.File(type='binary', file_types=[".json", ".txt"])
  874. with gr.Column():
  875. gr.Markdown('Download')
  876. download = gr.File()
  877. buttons["Download"] = gr.Button(value="Click me")
  878. with gr.Tab('Upload character'):
  879. with gr.Row():
  880. with gr.Column():
  881. gr.Markdown('1. Select the JSON file')
  882. upload_char = gr.File(type='binary', file_types=[".json"])
  883. with gr.Column():
  884. gr.Markdown('2. Select your character\'s profile picture (optional)')
  885. upload_img = gr.File(type='binary', file_types=["image"])
  886. buttons["Upload character"] = gr.Button(value="Submit")
  887. with gr.Tab('Upload your profile picture'):
  888. upload_img_me = gr.File(type='binary', file_types=["image"])
  889. with gr.Tab('Upload TavernAI Character Card'):
  890. upload_img_tavern = gr.File(type='binary', file_types=["image"])
  891. with gr.Tab("Generation settings"):
  892. with gr.Row():
  893. with gr.Column():
  894. max_new_tokens = 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'])
  895. with gr.Column():
  896. chat_prompt_size_slider = gr.Slider(minimum=settings['chat_prompt_size_min'], maximum=settings['chat_prompt_size_max'], step=1, label='Maximum prompt size in tokens', value=settings['chat_prompt_size'])
  897. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  898. if args.extensions is not None:
  899. with gr.Tab("Extensions"):
  900. create_extensions_block()
  901. input_params = [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size_slider]
  902. if args.picture:
  903. input_params.append(picture_select)
  904. function_call = "cai_chatbot_wrapper" if args.cai_chat else "chatbot_wrapper"
  905. gen_events.append(buttons["Generate"].click(eval(function_call), input_params, display, show_progress=args.no_stream, api_name="textgen"))
  906. gen_events.append(textbox.submit(eval(function_call), input_params, display, show_progress=args.no_stream))
  907. if args.picture:
  908. picture_select.upload(eval(function_call), input_params, display, show_progress=args.no_stream)
  909. gen_events.append(buttons["Regenerate"].click(regenerate_wrapper, input_params, display, show_progress=args.no_stream))
  910. gen_events.append(buttons["Impersonate"].click(impersonate_wrapper, input_params, textbox, show_progress=args.no_stream))
  911. buttons["Stop"].click(stop_everything_event, [], [], cancels=gen_events)
  912. buttons["Send last reply to input"].click(send_last_reply_to_input, [], textbox, show_progress=args.no_stream)
  913. buttons["Replace last reply"].click(replace_last_reply, [textbox, name1, name2], display, show_progress=args.no_stream)
  914. buttons["Clear history"].click(clear_chat_log, [character_menu, name1, name2], display)
  915. buttons["Remove last"].click(remove_last_message, [name1, name2], [display, textbox], show_progress=False)
  916. buttons["Download"].click(save_history, inputs=[], outputs=[download])
  917. buttons["Upload character"].click(upload_character, [upload_char, upload_img], [character_menu])
  918. # Clearing stuff and saving the history
  919. for i in ["Generate", "Regenerate", "Replace last reply"]:
  920. buttons[i].click(lambda x: "", textbox, textbox, show_progress=False)
  921. buttons[i].click(lambda : save_history(timestamp=False), [], [], show_progress=False)
  922. buttons["Clear history"].click(lambda : save_history(timestamp=False), [], [], show_progress=False)
  923. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  924. textbox.submit(lambda : save_history(timestamp=False), [], [], show_progress=False)
  925. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display])
  926. upload_chat_history.upload(load_history, [upload_chat_history, name1, name2], [])
  927. upload_img_tavern.upload(upload_tavern_character, [upload_img_tavern, name1, name2], [character_menu])
  928. upload_img_me.upload(upload_your_profile_picture, [upload_img_me], [])
  929. if args.picture:
  930. picture_select.upload(lambda : None, [], [picture_select], show_progress=False)
  931. if args.cai_chat:
  932. upload_chat_history.upload(redraw_html, [name1, name2], [display])
  933. upload_img_me.upload(redraw_html, [name1, name2], [display])
  934. else:
  935. upload_chat_history.upload(lambda : history['visible'], [], [display])
  936. upload_img_me.upload(lambda : history['visible'], [], [display])
  937. elif args.notebook:
  938. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  939. gr.Markdown(description)
  940. with gr.Tab('Raw'):
  941. textbox = gr.Textbox(value=default_text, lines=23)
  942. with gr.Tab('Markdown'):
  943. markdown = gr.Markdown()
  944. with gr.Tab('HTML'):
  945. html = gr.HTML()
  946. buttons["Generate"] = gr.Button("Generate")
  947. buttons["Stop"] = gr.Button("Stop")
  948. max_new_tokens = 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'])
  949. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  950. if args.extensions is not None:
  951. create_extensions_block()
  952. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  953. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream))
  954. buttons["Stop"].click(None, None, None, cancels=gen_events)
  955. else:
  956. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  957. gr.Markdown(description)
  958. with gr.Row():
  959. with gr.Column():
  960. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  961. max_new_tokens = 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'])
  962. buttons["Generate"] = gr.Button("Generate")
  963. with gr.Row():
  964. with gr.Column():
  965. buttons["Continue"] = gr.Button("Continue")
  966. with gr.Column():
  967. buttons["Stop"] = gr.Button("Stop")
  968. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  969. if args.extensions is not None:
  970. create_extensions_block()
  971. with gr.Column():
  972. with gr.Tab('Raw'):
  973. output_textbox = gr.Textbox(lines=15, label='Output')
  974. with gr.Tab('Markdown'):
  975. markdown = gr.Markdown()
  976. with gr.Tab('HTML'):
  977. html = gr.HTML()
  978. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  979. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  980. gen_events.append(buttons["Continue"].click(generate_reply, [output_textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  981. buttons["Stop"].click(None, None, None, cancels=gen_events)
  982. interface.queue()
  983. if args.listen:
  984. interface.launch(prevent_thread_lock=True, share=args.share, server_name="0.0.0.0", server_port=args.listen_port)
  985. else:
  986. interface.launch(prevent_thread_lock=True, share=args.share, server_port=args.listen_port)
  987. # I think that I will need this later
  988. while True:
  989. time.sleep(0.5)