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