text_generation.py 10 KB

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