text_generation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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, generate_params, eos_token=None, stopping_strings=[]):
  92. max_new_tokens = generate_params['max_new_tokens']
  93. seed = generate_params['seed']
  94. print(generate_params)
  95. print('---------------')
  96. clear_torch_cache()
  97. set_manual_seed(seed)
  98. shared.stop_everything = False
  99. updated_params = {}
  100. t0 = time.time()
  101. original_question = question
  102. if not shared.is_chat():
  103. question = apply_extensions(question, "input")
  104. if shared.args.verbose:
  105. print(f"\n\n{question}\n--------------------\n")
  106. # These models are not part of Hugging Face, so we handle them
  107. # separately and terminate the function call earlier
  108. if any((shared.is_RWKV, shared.is_llamacpp)):
  109. for k in ['temperature', 'top_p', 'top_k', 'repetition_penalty']:
  110. updated_params[k] = generate_params[k]
  111. updated_params["token_count"] = generate_params["max_new_tokens"]
  112. try:
  113. if shared.args.no_stream:
  114. reply = shared.model.generate(context=question, **updated_params)
  115. output = original_question+reply
  116. if not shared.is_chat():
  117. reply = original_question + apply_extensions(reply, "output")
  118. yield formatted_outputs(reply, shared.model_name)
  119. else:
  120. if not shared.is_chat():
  121. yield formatted_outputs(question, shared.model_name)
  122. # RWKV has proper streaming, which is very nice.
  123. # No need to generate 8 tokens at a time.
  124. for reply in shared.model.generate_with_streaming(context=question, **updated_params):
  125. output = original_question+reply
  126. if not shared.is_chat():
  127. reply = original_question + apply_extensions(reply, "output")
  128. yield formatted_outputs(reply, shared.model_name)
  129. except Exception:
  130. traceback.print_exc()
  131. finally:
  132. t1 = time.time()
  133. original_tokens = len(encode(original_question)[0])
  134. new_tokens = len(encode(output)[0]) - original_tokens
  135. print(f"Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens})")
  136. return
  137. input_ids = encode(question, max_new_tokens)
  138. original_input_ids = input_ids
  139. output = input_ids[0]
  140. cuda = not any((shared.args.cpu, shared.args.deepspeed, shared.args.flexgen))
  141. eos_token_ids = [shared.tokenizer.eos_token_id] if shared.tokenizer.eos_token_id is not None else []
  142. if eos_token is not None:
  143. eos_token_ids.append(int(encode(eos_token)[0][-1]))
  144. stopping_criteria_list = transformers.StoppingCriteriaList()
  145. if type(stopping_strings) is list and len(stopping_strings) > 0:
  146. t = [encode(string, 0, add_special_tokens=False) for string in stopping_strings]
  147. stopping_criteria_list.append(_SentinelTokenStoppingCriteria(sentinel_token_ids=t, starting_idx=len(input_ids[0])))
  148. updated_params["max_new_tokens"] = max_new_tokens
  149. if not shared.args.flexgen:
  150. updated_params["eos_token_id"] = eos_token_ids
  151. updated_params["stopping_criteria"] = stopping_criteria_list
  152. 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"]:
  153. updated_params[k] = generate_params[k]
  154. if shared.args.no_stream:
  155. updated_params["min_length"] = 0
  156. else:
  157. for k in ["do_sample", "temperature"]:
  158. updated_params[k] = generate_params[k]
  159. updated_params["stop"] = generate_params["eos_token_ids"][-1]
  160. if not shared.args.no_stream:
  161. updated_params["max_new_tokens"] = 8
  162. print(updated_params)
  163. if shared.args.no_cache:
  164. updated_params.update({"use_cache": False})
  165. if shared.args.deepspeed:
  166. updated_params.update({"synced_gpus": True})
  167. if shared.soft_prompt:
  168. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  169. updated_params.update({"inputs_embeds": inputs_embeds})
  170. updated_params.update({"inputs": filler_input_ids})
  171. else:
  172. updated_params.update({"inputs": input_ids})
  173. try:
  174. # Generate the entire reply at once.
  175. if shared.args.no_stream:
  176. with torch.no_grad():
  177. output = shared.model.generate(**updated_params)[0]
  178. if cuda:
  179. output = output.cuda()
  180. if shared.soft_prompt:
  181. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  182. new_tokens = len(output) - len(input_ids[0])
  183. reply = decode(output[-new_tokens:])
  184. if not shared.is_chat():
  185. reply = original_question + apply_extensions(reply, "output")
  186. yield formatted_outputs(reply, shared.model_name)
  187. # Stream the reply 1 token at a time.
  188. # This is based on the trick of using 'stopping_criteria' to create an iterator.
  189. elif not shared.args.flexgen:
  190. def generate_with_callback(callback=None, **kwargs):
  191. kwargs['stopping_criteria'].append(Stream(callback_func=callback))
  192. clear_torch_cache()
  193. with torch.no_grad():
  194. shared.model.generate(**kwargs)
  195. def generate_with_streaming(**kwargs):
  196. return Iteratorize(generate_with_callback, kwargs, callback=None)
  197. if not shared.is_chat():
  198. yield formatted_outputs(original_question, shared.model_name)
  199. with generate_with_streaming(**updated_params) as generator:
  200. for output in generator:
  201. if shared.soft_prompt:
  202. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  203. new_tokens = len(output) - len(input_ids[0])
  204. reply = decode(output[-new_tokens:])
  205. if not shared.is_chat():
  206. reply = original_question + apply_extensions(reply, "output")
  207. if output[-1] in eos_token_ids:
  208. break
  209. yield formatted_outputs(reply, shared.model_name)
  210. # Stream the output naively for FlexGen since it doesn't support 'stopping_criteria'
  211. else:
  212. for i in range(max_new_tokens//8+1):
  213. clear_torch_cache()
  214. with torch.no_grad():
  215. output = shared.model.generate(**updated_params)[0]
  216. if shared.soft_prompt:
  217. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  218. new_tokens = len(output) - len(original_input_ids[0])
  219. reply = decode(output[-new_tokens:])
  220. if not shared.is_chat():
  221. reply = original_question + apply_extensions(reply, "output")
  222. if np.count_nonzero(np.isin(input_ids[0], eos_token_ids)) < np.count_nonzero(np.isin(output, eos_token_ids)):
  223. break
  224. yield formatted_outputs(reply, shared.model_name)
  225. input_ids = np.reshape(output, (1, output.shape[0]))
  226. if shared.soft_prompt:
  227. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  228. updated_params.update({"inputs_embeds": inputs_embeds})
  229. updated_params.update({"inputs": filler_input_ids})
  230. else:
  231. updated_params.update({"inputs": input_ids})
  232. yield formatted_outputs(reply, shared.model_name)
  233. except Exception:
  234. traceback.print_exc()
  235. finally:
  236. t1 = time.time()
  237. original_tokens = len(original_input_ids[0])
  238. new_tokens = len(output)-original_tokens
  239. print(f"Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens})")
  240. return