text_generation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import gc
  2. import re
  3. import time
  4. import traceback
  5. import numpy as np
  6. import torch
  7. import transformers
  8. import modules.shared as shared
  9. from modules.callbacks import (Iteratorize, Stream,
  10. _SentinelTokenStoppingCriteria)
  11. from modules.extensions import apply_extensions
  12. from modules.html_generator import generate_4chan_html, generate_basic_html
  13. from modules.models import local_rank
  14. def get_max_prompt_length(tokens):
  15. max_length = 2048-tokens
  16. if shared.soft_prompt:
  17. max_length -= shared.soft_prompt_tensor.shape[1]
  18. return max_length
  19. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  20. if any((shared.is_RWKV, shared.is_llamacpp)):
  21. input_ids = shared.tokenizer.encode(str(prompt))
  22. input_ids = np.array(input_ids).reshape(1, len(input_ids))
  23. return input_ids
  24. else:
  25. 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)
  26. if shared.args.cpu:
  27. return input_ids
  28. elif shared.args.flexgen:
  29. return input_ids.numpy()
  30. elif shared.args.deepspeed:
  31. return input_ids.to(device=local_rank)
  32. elif torch.has_mps:
  33. device = torch.device('mps')
  34. return input_ids.to(device)
  35. else:
  36. return input_ids.cuda()
  37. def decode(output_ids):
  38. # Open Assistant relies on special tokens like <|endoftext|>
  39. if re.match('.*(oasst|galactica)-*', shared.model_name.lower()):
  40. return shared.tokenizer.decode(output_ids, skip_special_tokens=False)
  41. else:
  42. reply = shared.tokenizer.decode(output_ids, skip_special_tokens=True)
  43. reply = reply.replace(r'<|endoftext|>', '')
  44. return reply
  45. def generate_softprompt_input_tensors(input_ids):
  46. inputs_embeds = shared.model.transformer.wte(input_ids)
  47. inputs_embeds = torch.cat((shared.soft_prompt_tensor, inputs_embeds), dim=1)
  48. filler_input_ids = torch.zeros((1, inputs_embeds.shape[1]), dtype=input_ids.dtype).to(shared.model.device)
  49. #filler_input_ids += shared.model.config.bos_token_id # setting dummy input_ids to bos tokens
  50. return inputs_embeds, filler_input_ids
  51. # Removes empty replies from gpt4chan outputs
  52. def fix_gpt4chan(s):
  53. for i in range(10):
  54. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  55. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  56. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  57. return s
  58. # Fix the LaTeX equations in galactica
  59. def fix_galactica(s):
  60. s = s.replace(r'\[', r'$')
  61. s = s.replace(r'\]', r'$')
  62. s = s.replace(r'\(', r'$')
  63. s = s.replace(r'\)', r'$')
  64. s = s.replace(r'$$', r'$')
  65. s = re.sub(r'\n', r'\n\n', s)
  66. s = re.sub(r"\n{3,}", "\n\n", s)
  67. return s
  68. def formatted_outputs(reply, model_name):
  69. if not shared.is_chat():
  70. if 'galactica' in model_name.lower():
  71. reply = fix_galactica(reply)
  72. return reply, reply, generate_basic_html(reply)
  73. elif any((k in shared.model_name.lower() for k in ['gpt4chan', 'gpt-4chan'])):
  74. reply = fix_gpt4chan(reply)
  75. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  76. else:
  77. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  78. else:
  79. return reply
  80. def clear_torch_cache():
  81. gc.collect()
  82. if not shared.args.cpu:
  83. torch.cuda.empty_cache()
  84. def set_manual_seed(seed):
  85. if seed != -1:
  86. torch.manual_seed(seed)
  87. if torch.cuda.is_available():
  88. torch.cuda.manual_seed_all(seed)
  89. def stop_everything_event():
  90. shared.stop_everything = True
  91. def generate_reply(question, max_new_tokens, generation_params, seed, eos_token=None, stopping_strings=[]):
  92. print(generation_params)
  93. print('---------------')
  94. clear_torch_cache()
  95. set_manual_seed(seed)
  96. shared.stop_everything = False
  97. updated_params = {}
  98. t0 = time.time()
  99. original_question = question
  100. if not shared.is_chat():
  101. question = apply_extensions(question, "input")
  102. if shared.args.verbose:
  103. print(f"\n\n{question}\n--------------------\n")
  104. # These models are not part of Hugging Face, so we handle them
  105. # separately and terminate the function call earlier
  106. if any((shared.is_RWKV, shared.is_llamacpp)):
  107. for k in ['temperature', 'top_p', 'top_k', 'repetition_penalty']:
  108. updated_params[k] = generation_params[k]
  109. updated_params["token_count"] = generation_params["max_new_tokens"]
  110. try:
  111. if shared.args.no_stream:
  112. reply = shared.model.generate(context=question, **updated_params)
  113. output = original_question+reply
  114. if not shared.is_chat():
  115. reply = original_question + apply_extensions(reply, "output")
  116. yield formatted_outputs(reply, shared.model_name)
  117. else:
  118. if not shared.is_chat():
  119. yield formatted_outputs(question, shared.model_name)
  120. # RWKV has proper streaming, which is very nice.
  121. # No need to generate 8 tokens at a time.
  122. for reply in shared.model.generate_with_streaming(context=question, **updated_params):
  123. output = original_question+reply
  124. if not shared.is_chat():
  125. reply = original_question + apply_extensions(reply, "output")
  126. yield formatted_outputs(reply, shared.model_name)
  127. except Exception:
  128. traceback.print_exc()
  129. finally:
  130. t1 = time.time()
  131. original_tokens = len(encode(original_question)[0])
  132. new_tokens = len(encode(output)[0]) - original_tokens
  133. print(f"Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens})")
  134. return
  135. input_ids = encode(question, max_new_tokens)
  136. original_input_ids = input_ids
  137. output = input_ids[0]
  138. cuda = not any((shared.args.cpu, shared.args.deepspeed, shared.args.flexgen))
  139. eos_token_ids = [shared.tokenizer.eos_token_id] if shared.tokenizer.eos_token_id is not None else []
  140. if eos_token is not None:
  141. eos_token_ids.append(int(encode(eos_token)[0][-1]))
  142. stopping_criteria_list = transformers.StoppingCriteriaList()
  143. if type(stopping_strings) is list and len(stopping_strings) > 0:
  144. t = [encode(string, 0, add_special_tokens=False) for string in stopping_strings]
  145. stopping_criteria_list.append(_SentinelTokenStoppingCriteria(sentinel_token_ids=t, starting_idx=len(input_ids[0])))
  146. updated_params["max_new_tokens"] = max_new_tokens
  147. if not shared.args.flexgen:
  148. updated_params["eos_token_id"] = eos_token_ids
  149. updated_params["stopping_criteria"] = stopping_criteria_list
  150. for k in ["do_sample", "temperature", "top_p", "typical_p", "repetition_penalty", "encoder_repetition_penalty", "top_k", "min_length", "no_repeat_ngram_size", "num_beams", "penalty_alpha", "length_penalty", "early_stopping"]:
  151. updated_params[k] = generation_params[k]
  152. if shared.args.no_stream:
  153. updated_params["min_length"] = 0
  154. else:
  155. for k in ["do_sample", "temperature"]:
  156. updated_params[k] = generation_params[k]
  157. updated_params["stop"] = generation_params["eos_token_ids"][-1]
  158. if not shared.args.no_stream:
  159. updated_params["max_new_tokens"] = 8
  160. print(updated_params)
  161. if shared.args.no_cache:
  162. updated_params.update({"use_cache": False})
  163. if shared.args.deepspeed:
  164. updated_params.update({"synced_gpus": True})
  165. if shared.soft_prompt:
  166. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  167. updated_params.update({"inputs_embeds": inputs_embeds})
  168. updated_params.update({"inputs": filler_input_ids})
  169. else:
  170. updated_params.update({"inputs": input_ids})
  171. try:
  172. # Generate the entire reply at once.
  173. if shared.args.no_stream:
  174. with torch.no_grad():
  175. output = shared.model.generate(**updated_params)[0]
  176. if cuda:
  177. output = output.cuda()
  178. if shared.soft_prompt:
  179. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  180. new_tokens = len(output) - len(input_ids[0])
  181. reply = decode(output[-new_tokens:])
  182. if not shared.is_chat():
  183. reply = original_question + apply_extensions(reply, "output")
  184. yield formatted_outputs(reply, shared.model_name)
  185. # Stream the reply 1 token at a time.
  186. # This is based on the trick of using 'stopping_criteria' to create an iterator.
  187. elif not shared.args.flexgen:
  188. def generate_with_callback(callback=None, **kwargs):
  189. kwargs['stopping_criteria'].append(Stream(callback_func=callback))
  190. clear_torch_cache()
  191. with torch.no_grad():
  192. shared.model.generate(**kwargs)
  193. def generate_with_streaming(**kwargs):
  194. return Iteratorize(generate_with_callback, kwargs, callback=None)
  195. if not shared.is_chat():
  196. yield formatted_outputs(original_question, shared.model_name)
  197. with generate_with_streaming(**updated_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. new_tokens = len(output) - len(input_ids[0])
  202. reply = decode(output[-new_tokens:])
  203. if not shared.is_chat():
  204. reply = original_question + apply_extensions(reply, "output")
  205. if output[-1] in eos_token_ids:
  206. break
  207. yield formatted_outputs(reply, shared.model_name)
  208. # Stream the output naively for FlexGen since it doesn't support 'stopping_criteria'
  209. else:
  210. for i in range(max_new_tokens//8+1):
  211. clear_torch_cache()
  212. with torch.no_grad():
  213. output = shared.model.generate(**updated_params)[0]
  214. if shared.soft_prompt:
  215. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  216. new_tokens = len(output) - len(original_input_ids[0])
  217. reply = decode(output[-new_tokens:])
  218. if not shared.is_chat():
  219. reply = original_question + apply_extensions(reply, "output")
  220. if np.count_nonzero(np.isin(input_ids[0], eos_token_ids)) < np.count_nonzero(np.isin(output, eos_token_ids)):
  221. break
  222. yield formatted_outputs(reply, shared.model_name)
  223. input_ids = np.reshape(output, (1, output.shape[0]))
  224. if shared.soft_prompt:
  225. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  226. updated_params.update({"inputs_embeds": inputs_embeds})
  227. updated_params.update({"inputs": filler_input_ids})
  228. else:
  229. updated_params.update({"inputs": input_ids})
  230. yield formatted_outputs(reply, shared.model_name)
  231. except Exception:
  232. traceback.print_exc()
  233. finally:
  234. t1 = time.time()
  235. original_tokens = len(original_input_ids[0])
  236. new_tokens = len(output)-original_tokens
  237. print(f"Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens})")
  238. return