dwolfe66/text-generation-webui-space
1
1import gc2import re3import time4 5import numpy as np6import torch7import transformers8 9import modules.shared as shared10from modules.callbacks import (Iteratorize, Stream,11 _SentinelTokenStoppingCriteria)12from modules.extensions import apply_extensions13from modules.html_generator import generate_4chan_html, generate_basic_html14from modules.models import local_rank15 16 17def get_max_prompt_length(tokens):18 max_length = 2048-tokens19 if shared.soft_prompt:20 max_length -= shared.soft_prompt_tensor.shape[1]21 return max_length22 23def encode(prompt, tokens_to_generate=0, add_special_tokens=True):24 if shared.is_RWKV:25 input_ids = shared.tokenizer.encode(str(prompt))26 input_ids = np.array(input_ids).reshape(1, len(input_ids))27 return input_ids28 else:29 input_ids = shared.tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=get_max_prompt_length(tokens_to_generate), add_special_tokens=add_special_tokens)30 if shared.args.cpu:31 return input_ids32 elif shared.args.flexgen:33 return input_ids.numpy()34 elif shared.args.deepspeed:35 return input_ids.to(device=local_rank)36 else:37 return input_ids.cuda()38 39def decode(output_ids):40 # Open Assistant relies on special tokens like <|endoftext|>41 if re.match('oasst-*', shared.model_name.lower()):42 return shared.tokenizer.decode(output_ids, skip_special_tokens=False)43 else:44 reply = shared.tokenizer.decode(output_ids, skip_special_tokens=True)45 reply = reply.replace(r'<|endoftext|>', '')46 return reply47 48def generate_softprompt_input_tensors(input_ids):49 inputs_embeds = shared.model.transformer.wte(input_ids)50 inputs_embeds = torch.cat((shared.soft_prompt_tensor, inputs_embeds), dim=1)51 filler_input_ids = torch.zeros((1, inputs_embeds.shape[1]), dtype=input_ids.dtype).to(shared.model.device)52 #filler_input_ids += shared.model.config.bos_token_id # setting dummy input_ids to bos tokens53 return inputs_embeds, filler_input_ids54 55# Removes empty replies from gpt4chan outputs56def fix_gpt4chan(s):57 for i in range(10):58 s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)59 s = re.sub("--- [0-9]*\n *\n---", "---", s)60 s = re.sub("--- [0-9]*\n\n\n---", "---", s)61 return s62 63# Fix the LaTeX equations in galactica64def fix_galactica(s):65 s = s.replace(r'\[', r'$')66 s = s.replace(r'\]', r'$')67 s = s.replace(r'\(', r'$')68 s = s.replace(r'\)', r'$')69 s = s.replace(r'$$', r'$')70 s = re.sub(r'\n', r'\n\n', s)71 s = re.sub(r"\n{3,}", "\n\n", s)72 return s73 74def formatted_outputs(reply, model_name):75 if not (shared.args.chat or shared.args.cai_chat):76 if model_name.lower().startswith('galactica'):77 reply = fix_galactica(reply)78 return reply, reply, generate_basic_html(reply)79 elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):80 reply = fix_gpt4chan(reply)81 return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)82 else:83 return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)84 else:85 return reply86 87def clear_torch_cache():88 gc.collect()89 if not shared.args.cpu:90 torch.cuda.empty_cache()91 92def generate_reply(question, max_new_tokens, 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, eos_token=None, stopping_string=None):93 clear_torch_cache()94 t0 = time.time()95 96 # These models are not part of Hugging Face, so we handle them97 # separately and terminate the function call earlier98 if shared.is_RWKV:99 try:100 if shared.args.no_stream:101 reply = shared.model.generate(context=question, token_count=max_new_tokens, temperature=temperature, top_p=top_p, top_k=top_k)102 yield formatted_outputs(reply, shared.model_name)103 else:104 yield formatted_outputs(question, shared.model_name)105 # RWKV has proper streaming, which is very nice.106 # No need to generate 8 tokens at a time.107 for reply in shared.model.generate_with_streaming(context=question, token_count=max_new_tokens, temperature=temperature, top_p=top_p, top_k=top_k):108 yield formatted_outputs(reply, shared.model_name)109 finally:110 t1 = time.time()111 output = encode(reply)[0]112 input_ids = encode(question)113 print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output)-len(input_ids[0]))/(t1-t0):.2f} tokens/s, {len(output)-len(input_ids[0])} tokens)")114 return115 116 original_question = question117 if not (shared.args.chat or shared.args.cai_chat):118 question = apply_extensions(question, "input")119 if shared.args.verbose:120 print(f"\n\n{question}\n--------------------\n")121 122 input_ids = encode(question, max_new_tokens)123 original_input_ids = input_ids124 output = input_ids[0]125 cuda = "" if (shared.args.cpu or shared.args.deepspeed or shared.args.flexgen) else ".cuda()"126 eos_token_ids = [shared.tokenizer.eos_token_id] if shared.tokenizer.eos_token_id is not None else []127 if eos_token is not None:128 eos_token_ids.append(int(encode(eos_token)[0][-1]))129 stopping_criteria_list = transformers.StoppingCriteriaList()130 if stopping_string is not None:131 # Copied from https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py132 t = encode(stopping_string, 0, add_special_tokens=False)133 stopping_criteria_list.append(_SentinelTokenStoppingCriteria(sentinel_token_ids=t, starting_idx=len(input_ids[0])))134 135 if not shared.args.flexgen:136 generate_params = [137 f"max_new_tokens=max_new_tokens",138 f"eos_token_id={eos_token_ids}",139 f"stopping_criteria=stopping_criteria_list",140 f"do_sample={do_sample}",141 f"temperature={temperature}",142 f"top_p={top_p}",143 f"typical_p={typical_p}",144 f"repetition_penalty={repetition_penalty}",145 f"top_k={top_k}",146 f"min_length={min_length if shared.args.no_stream else 0}",147 f"no_repeat_ngram_size={no_repeat_ngram_size}",148 f"num_beams={num_beams}",149 f"penalty_alpha={penalty_alpha}",150 f"length_penalty={length_penalty}",151 f"early_stopping={early_stopping}",152 ]153 else:154 generate_params = [155 f"max_new_tokens={max_new_tokens if shared.args.no_stream else 8}",156 f"do_sample={do_sample}",157 f"temperature={temperature}",158 f"stop={eos_token_ids[-1]}",159 ]160 if shared.args.deepspeed:161 generate_params.append("synced_gpus=True")162 if shared.soft_prompt:163 inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)164 generate_params.insert(0, "inputs_embeds=inputs_embeds")165 generate_params.insert(0, "inputs=filler_input_ids")166 else:167 generate_params.insert(0, "inputs=input_ids")168 169 try:170 # Generate the entire reply at once.171 if shared.args.no_stream:172 with torch.no_grad():173 output = eval(f"shared.model.generate({', '.join(generate_params)}){cuda}")[0]174 if shared.soft_prompt:175 output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))176 177 reply = decode(output)178 if not (shared.args.chat or shared.args.cai_chat):179 reply = original_question + apply_extensions(reply[len(question):], "output")180 181 yield formatted_outputs(reply, shared.model_name)182 183 # Stream the reply 1 token at a time.184 # This is based on the trick of using 'stopping_criteria' to create an iterator.185 elif not shared.args.flexgen:186 187 def generate_with_callback(callback=None, **kwargs):188 kwargs['stopping_criteria'].append(Stream(callback_func=callback))189 clear_torch_cache()190 with torch.no_grad():191 shared.model.generate(**kwargs)192 193 def generate_with_streaming(**kwargs):194 return Iteratorize(generate_with_callback, kwargs, callback=None)195 196 yield formatted_outputs(original_question, shared.model_name)197 with eval(f"generate_with_streaming({', '.join(generate_params)})") as generator:198 for output in generator:199 if shared.soft_prompt:200 output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))201 reply = decode(output)202 203 if not (shared.args.chat or shared.args.cai_chat):204 reply = original_question + apply_extensions(reply[len(question):], "output")205 206 if output[-1] in eos_token_ids:207 break208 yield formatted_outputs(reply, shared.model_name)209 210 yield formatted_outputs(reply, shared.model_name)211 212 # Stream the output naively for FlexGen since it doesn't support 'stopping_criteria'213 else:214 for i in range(max_new_tokens//8+1):215 clear_torch_cache()216 with torch.no_grad():217 output = eval(f"shared.model.generate({', '.join(generate_params)})")[0]218 if shared.soft_prompt:219 output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))220 reply = decode(output)221 222 if not (shared.args.chat or shared.args.cai_chat):223 reply = original_question + apply_extensions(reply[len(question):], "output")224 225 if np.count_nonzero(np.isin(input_ids[0], eos_token_ids)) < np.count_nonzero(np.isin(output, eos_token_ids)):226 break227 yield formatted_outputs(reply, shared.model_name)228 229 input_ids = np.reshape(output, (1, output.shape[0]))230 if shared.soft_prompt:231 inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)232 233 yield formatted_outputs(reply, shared.model_name)234 235 finally:236 t1 = time.time()237 print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output)-len(original_input_ids[0]))/(t1-t0):.2f} tokens/s, {len(output)-len(original_input_ids[0])} tokens)")238 return239 