server.py 56 KB

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