server.py 56 KB

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