text_generation.py 12 KB

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