text_generation.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import gc
  2. import re
  3. import time
  4. import numpy as np
  5. import torch
  6. import transformers
  7. import modules.shared as shared
  8. from modules.callbacks import (Iteratorize, Stream,
  9. _SentinelTokenStoppingCriteria)
  10. from modules.extensions import apply_extensions
  11. from modules.html_generator import generate_4chan_html, generate_basic_html
  12. from modules.models import local_rank
  13. def get_max_prompt_length(tokens):
  14. max_length = 2048-tokens
  15. if shared.soft_prompt:
  16. max_length -= shared.soft_prompt_tensor.shape[1]
  17. return max_length
  18. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  19. if shared.is_RWKV:
  20. input_ids = shared.tokenizer.encode(str(prompt))
  21. input_ids = np.array(input_ids).reshape(1, len(input_ids))
  22. return input_ids
  23. else:
  24. 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)
  25. if shared.args.cpu:
  26. return input_ids
  27. elif shared.args.flexgen:
  28. return input_ids.numpy()
  29. elif shared.args.deepspeed:
  30. return input_ids.to(device=local_rank)
  31. else:
  32. return input_ids.cuda()
  33. def decode(output_ids):
  34. reply = shared.tokenizer.decode(output_ids, skip_special_tokens=True)
  35. reply = reply.replace(r'<|endoftext|>', '')
  36. return reply
  37. def generate_softprompt_input_tensors(input_ids):
  38. inputs_embeds = shared.model.transformer.wte(input_ids)
  39. inputs_embeds = torch.cat((shared.soft_prompt_tensor, inputs_embeds), dim=1)
  40. filler_input_ids = torch.zeros((1, inputs_embeds.shape[1]), dtype=input_ids.dtype).to(shared.model.device)
  41. #filler_input_ids += shared.model.config.bos_token_id # setting dummy input_ids to bos tokens
  42. return inputs_embeds, filler_input_ids
  43. # Removes empty replies from gpt4chan outputs
  44. def fix_gpt4chan(s):
  45. for i in range(10):
  46. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  47. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  48. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  49. return s
  50. # Fix the LaTeX equations in galactica
  51. def fix_galactica(s):
  52. s = s.replace(r'\[', r'$')
  53. s = s.replace(r'\]', r'$')
  54. s = s.replace(r'\(', r'$')
  55. s = s.replace(r'\)', r'$')
  56. s = s.replace(r'$$', r'$')
  57. s = re.sub(r'\n', r'\n\n', s)
  58. s = re.sub(r"\n{3,}", "\n\n", s)
  59. return s
  60. def formatted_outputs(reply, model_name):
  61. if not (shared.args.chat or shared.args.cai_chat):
  62. if model_name.lower().startswith('galactica'):
  63. reply = fix_galactica(reply)
  64. return reply, reply, generate_basic_html(reply)
  65. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  66. reply = fix_gpt4chan(reply)
  67. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  68. else:
  69. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  70. else:
  71. return reply
  72. def clear_torch_cache():
  73. gc.collect()
  74. if not shared.args.cpu:
  75. torch.cuda.empty_cache()
  76. def 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):
  77. clear_torch_cache()
  78. t0 = time.time()
  79. # These models are not part of Hugging Face, so we handle them
  80. # separately and terminate the function call earlier
  81. if shared.is_RWKV:
  82. if shared.args.no_stream:
  83. reply = shared.model.generate(context=question, token_count=max_new_tokens, temperature=temperature, top_p=top_p, top_k=top_k)
  84. yield formatted_outputs(reply, shared.model_name)
  85. else:
  86. yield formatted_outputs(question, shared.model_name)
  87. # RWKV has proper streaming, which is very nice.
  88. # No need to generate 8 tokens at a time.
  89. 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):
  90. yield formatted_outputs(reply, shared.model_name)
  91. t1 = time.time()
  92. output = encode(reply)[0]
  93. input_ids = encode(question)
  94. 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)")
  95. return
  96. original_question = question
  97. if not (shared.args.chat or shared.args.cai_chat):
  98. question = apply_extensions(question, "input")
  99. if shared.args.verbose:
  100. print(f"\n\n{question}\n--------------------\n")
  101. input_ids = encode(question, max_new_tokens)
  102. original_input_ids = input_ids
  103. output = input_ids[0]
  104. cuda = "" if (shared.args.cpu or shared.args.deepspeed or shared.args.flexgen) else ".cuda()"
  105. n = shared.tokenizer.eos_token_id if eos_token is None else int(encode(eos_token)[0][-1])
  106. stopping_criteria_list = transformers.StoppingCriteriaList()
  107. if stopping_string is not None:
  108. # Copied from https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py
  109. t = encode(stopping_string, 0, add_special_tokens=False)
  110. stopping_criteria_list.append(_SentinelTokenStoppingCriteria(sentinel_token_ids=t, starting_idx=len(input_ids[0])))
  111. if not shared.args.flexgen:
  112. generate_params = [
  113. f"max_new_tokens=max_new_tokens",
  114. f"eos_token_id={n}",
  115. f"stopping_criteria=stopping_criteria_list",
  116. f"do_sample={do_sample}",
  117. f"temperature={temperature}",
  118. f"top_p={top_p}",
  119. f"typical_p={typical_p}",
  120. f"repetition_penalty={repetition_penalty}",
  121. f"top_k={top_k}",
  122. f"min_length={min_length if shared.args.no_stream else 0}",
  123. f"no_repeat_ngram_size={no_repeat_ngram_size}",
  124. f"num_beams={num_beams}",
  125. f"penalty_alpha={penalty_alpha}",
  126. f"length_penalty={length_penalty}",
  127. f"early_stopping={early_stopping}",
  128. ]
  129. else:
  130. generate_params = [
  131. f"max_new_tokens={max_new_tokens if shared.args.no_stream else 8}",
  132. f"do_sample={do_sample}",
  133. f"temperature={temperature}",
  134. f"stop={n}",
  135. ]
  136. if shared.args.deepspeed:
  137. generate_params.append("synced_gpus=True")
  138. if shared.soft_prompt:
  139. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  140. generate_params.insert(0, "inputs_embeds=inputs_embeds")
  141. generate_params.insert(0, "inputs=filler_input_ids")
  142. else:
  143. generate_params.insert(0, "inputs=input_ids")
  144. # Generate the entire reply at once.
  145. if shared.args.no_stream:
  146. with torch.no_grad():
  147. output = eval(f"shared.model.generate({', '.join(generate_params)}){cuda}")[0]
  148. if shared.soft_prompt:
  149. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  150. reply = decode(output)
  151. if not (shared.args.chat or shared.args.cai_chat):
  152. reply = original_question + apply_extensions(reply[len(question):], "output")
  153. yield formatted_outputs(reply, shared.model_name)
  154. # Stream the reply 1 token at a time.
  155. # This is based on the trick of using 'stopping_criteria' to create an iterator.
  156. elif not shared.args.flexgen:
  157. def generate_with_callback(callback=None, **kwargs):
  158. kwargs['stopping_criteria'].append(Stream(callback_func=callback))
  159. clear_torch_cache()
  160. with torch.no_grad():
  161. shared.model.generate(**kwargs)
  162. def generate_with_streaming(**kwargs):
  163. return Iteratorize(generate_with_callback, kwargs, callback=None)
  164. yield formatted_outputs(original_question, shared.model_name)
  165. with eval(f"generate_with_streaming({', '.join(generate_params)})") as generator:
  166. for output in generator:
  167. if shared.soft_prompt:
  168. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  169. reply = decode(output)
  170. if not (shared.args.chat or shared.args.cai_chat):
  171. reply = original_question + apply_extensions(reply[len(question):], "output")
  172. yield formatted_outputs(reply, shared.model_name)
  173. if output[-1] == n:
  174. break
  175. # Stream the output naively for FlexGen since it doesn't support 'stopping_criteria'
  176. else:
  177. for i in range(max_new_tokens//8+1):
  178. clear_torch_cache()
  179. with torch.no_grad():
  180. output = eval(f"shared.model.generate({', '.join(generate_params)})")[0]
  181. if shared.soft_prompt:
  182. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  183. reply = decode(output)
  184. if not (shared.args.chat or shared.args.cai_chat):
  185. reply = original_question + apply_extensions(reply[len(question):], "output")
  186. yield formatted_outputs(reply, shared.model_name)
  187. if np.count_nonzero(input_ids[0] == n) < np.count_nonzero(output == n):
  188. break
  189. input_ids = np.reshape(output, (1, output.shape[0]))
  190. if shared.soft_prompt:
  191. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  192. t1 = time.time()
  193. 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)")
  194. return