server.py 50 KB

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