generate.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import sys
  2. import fire
  3. import gradio as gr
  4. import torch
  5. import transformers
  6. from peft import PeftModel
  7. from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
  8. if torch.cuda.is_available():
  9. device = "cuda"
  10. else:
  11. device = "cpu"
  12. try:
  13. if torch.backends.mps.is_available():
  14. device = "mps"
  15. except: # noqa: E722
  16. pass
  17. def main(
  18. load_8bit: bool = False,
  19. base_model: str = "",
  20. lora_weights: str = "tloen/alpaca-lora-7b",
  21. ):
  22. assert (
  23. base_model
  24. ), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
  25. tokenizer = LlamaTokenizer.from_pretrained(base_model)
  26. if device == "cuda":
  27. model = LlamaForCausalLM.from_pretrained(
  28. base_model,
  29. load_in_8bit=load_8bit,
  30. torch_dtype=torch.float16,
  31. device_map="auto",
  32. )
  33. model = PeftModel.from_pretrained(
  34. model,
  35. lora_weights,
  36. torch_dtype=torch.float16,
  37. )
  38. elif device == "mps":
  39. model = LlamaForCausalLM.from_pretrained(
  40. base_model,
  41. device_map={"": device},
  42. torch_dtype=torch.float16,
  43. )
  44. model = PeftModel.from_pretrained(
  45. model,
  46. lora_weights,
  47. device_map={"": device},
  48. torch_dtype=torch.float16,
  49. )
  50. else:
  51. model = LlamaForCausalLM.from_pretrained(
  52. base_model, device_map={"": device}, low_cpu_mem_usage=True
  53. )
  54. model = PeftModel.from_pretrained(
  55. model,
  56. lora_weights,
  57. device_map={"": device},
  58. )
  59. # unwind broken decapoda-research config
  60. model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
  61. model.config.bos_token_id = 1
  62. model.config.eos_token_id = 2
  63. if not load_8bit:
  64. model.half() # seems to fix bugs for some users.
  65. model.eval()
  66. if torch.__version__ >= "2" and sys.platform != "win32":
  67. model = torch.compile(model)
  68. def evaluate(
  69. instruction,
  70. input=None,
  71. temperature=0.1,
  72. top_p=0.75,
  73. top_k=40,
  74. num_beams=4,
  75. max_new_tokens=128,
  76. **kwargs,
  77. ):
  78. prompt = generate_prompt(instruction, input)
  79. inputs = tokenizer(prompt, return_tensors="pt")
  80. input_ids = inputs["input_ids"].to(device)
  81. generation_config = GenerationConfig(
  82. temperature=temperature,
  83. top_p=top_p,
  84. top_k=top_k,
  85. num_beams=num_beams,
  86. **kwargs,
  87. )
  88. with torch.no_grad():
  89. generation_output = model.generate(
  90. input_ids=input_ids,
  91. generation_config=generation_config,
  92. return_dict_in_generate=True,
  93. output_scores=True,
  94. max_new_tokens=max_new_tokens,
  95. )
  96. s = generation_output.sequences[0]
  97. output = tokenizer.decode(s)
  98. return output.split("### Response:")[1].strip()
  99. gr.Interface(
  100. fn=evaluate,
  101. inputs=[
  102. gr.components.Textbox(
  103. lines=2,
  104. label="Instruction",
  105. placeholder="Tell me about alpacas.",
  106. ),
  107. gr.components.Textbox(lines=2, label="Input", placeholder="none"),
  108. gr.components.Slider(
  109. minimum=0, maximum=1, value=0.1, label="Temperature"
  110. ),
  111. gr.components.Slider(
  112. minimum=0, maximum=1, value=0.75, label="Top p"
  113. ),
  114. gr.components.Slider(
  115. minimum=0, maximum=100, step=1, value=40, label="Top k"
  116. ),
  117. gr.components.Slider(
  118. minimum=1, maximum=4, step=1, value=4, label="Beams"
  119. ),
  120. gr.components.Slider(
  121. minimum=1, maximum=2000, step=1, value=128, label="Max tokens"
  122. ),
  123. ],
  124. outputs=[
  125. gr.inputs.Textbox(
  126. lines=5,
  127. label="Output",
  128. )
  129. ],
  130. title="🦙🌲 Alpaca-LoRA",
  131. description="Alpaca-LoRA is a 7B-parameter LLaMA model finetuned to follow instructions. It is trained on the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) dataset and makes use of the Huggingface LLaMA implementation. For more information, please visit [the project's website](https://github.com/tloen/alpaca-lora).", # noqa: E501
  132. ).launch()
  133. # Old testing code follows.
  134. """
  135. # testing code for readme
  136. for instruction in [
  137. "Tell me about alpacas.",
  138. "Tell me about the president of Mexico in 2019.",
  139. "Tell me about the king of France in 2019.",
  140. "List all Canadian provinces in alphabetical order.",
  141. "Write a Python program that prints the first 10 Fibonacci numbers.",
  142. "Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'.", # noqa: E501
  143. "Tell me five words that rhyme with 'shock'.",
  144. "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
  145. "Count up from 1 to 500.",
  146. ]:
  147. print("Instruction:", instruction)
  148. print("Response:", evaluate(instruction))
  149. print()
  150. """
  151. def generate_prompt(instruction, input=None):
  152. if input:
  153. return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. # noqa: E501
  154. ### Instruction:
  155. {instruction}
  156. ### Input:
  157. {input}
  158. ### Response:
  159. """
  160. else:
  161. return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request. # noqa: E501
  162. ### Instruction:
  163. {instruction}
  164. ### Response:
  165. """
  166. if __name__ == "__main__":
  167. fire.Fire(main)