generate.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. from utils.prompter import Prompter
  9. if torch.cuda.is_available():
  10. device = "cuda"
  11. else:
  12. device = "cpu"
  13. try:
  14. if torch.backends.mps.is_available():
  15. device = "mps"
  16. except: # noqa: E722
  17. pass
  18. def main(
  19. load_8bit: bool = False,
  20. base_model: str = "",
  21. lora_weights: str = "tloen/alpaca-lora-7b",
  22. prompt_template: str = "", # The prompt template to use, will default to alpaca.
  23. server_name: str = "127.0.0.1", # Allows to listen on all interfaces by providing '0.0.0.0'
  24. share_gradio: bool = False,
  25. ):
  26. assert (
  27. base_model
  28. ), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
  29. prompter = Prompter(prompt_template)
  30. tokenizer = LlamaTokenizer.from_pretrained(base_model)
  31. if device == "cuda":
  32. model = LlamaForCausalLM.from_pretrained(
  33. base_model,
  34. load_in_8bit=load_8bit,
  35. torch_dtype=torch.float16,
  36. device_map="auto",
  37. )
  38. model = PeftModel.from_pretrained(
  39. model,
  40. lora_weights,
  41. torch_dtype=torch.float16,
  42. )
  43. elif device == "mps":
  44. model = LlamaForCausalLM.from_pretrained(
  45. base_model,
  46. device_map={"": device},
  47. torch_dtype=torch.float16,
  48. )
  49. model = PeftModel.from_pretrained(
  50. model,
  51. lora_weights,
  52. device_map={"": device},
  53. torch_dtype=torch.float16,
  54. )
  55. else:
  56. model = LlamaForCausalLM.from_pretrained(
  57. base_model, device_map={"": device}, low_cpu_mem_usage=True
  58. )
  59. model = PeftModel.from_pretrained(
  60. model,
  61. lora_weights,
  62. device_map={"": device},
  63. )
  64. # unwind broken decapoda-research config
  65. model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
  66. model.config.bos_token_id = 1
  67. model.config.eos_token_id = 2
  68. if not load_8bit:
  69. model.half() # seems to fix bugs for some users.
  70. model.eval()
  71. if torch.__version__ >= "2" and sys.platform != "win32":
  72. model = torch.compile(model)
  73. def evaluate(
  74. instruction,
  75. input=None,
  76. temperature=0.1,
  77. top_p=0.75,
  78. top_k=40,
  79. num_beams=4,
  80. max_new_tokens=128,
  81. **kwargs,
  82. ):
  83. prompt = prompter.generate_prompt(instruction, input)
  84. inputs = tokenizer(prompt, return_tensors="pt")
  85. input_ids = inputs["input_ids"].to(device)
  86. generation_config = GenerationConfig(
  87. temperature=temperature,
  88. top_p=top_p,
  89. top_k=top_k,
  90. num_beams=num_beams,
  91. **kwargs,
  92. )
  93. with torch.no_grad():
  94. generation_output = model.generate(
  95. input_ids=input_ids,
  96. generation_config=generation_config,
  97. return_dict_in_generate=True,
  98. output_scores=True,
  99. max_new_tokens=max_new_tokens,
  100. )
  101. s = generation_output.sequences[0]
  102. output = tokenizer.decode(s)
  103. return prompter.get_response(output)
  104. gr.Interface(
  105. fn=evaluate,
  106. inputs=[
  107. gr.components.Textbox(
  108. lines=2,
  109. label="Instruction",
  110. placeholder="Tell me about alpacas.",
  111. ),
  112. gr.components.Textbox(lines=2, label="Input", placeholder="none"),
  113. gr.components.Slider(
  114. minimum=0, maximum=1, value=0.1, label="Temperature"
  115. ),
  116. gr.components.Slider(
  117. minimum=0, maximum=1, value=0.75, label="Top p"
  118. ),
  119. gr.components.Slider(
  120. minimum=0, maximum=100, step=1, value=40, label="Top k"
  121. ),
  122. gr.components.Slider(
  123. minimum=1, maximum=4, step=1, value=4, label="Beams"
  124. ),
  125. gr.components.Slider(
  126. minimum=1, maximum=2000, step=1, value=128, label="Max tokens"
  127. ),
  128. ],
  129. outputs=[
  130. gr.inputs.Textbox(
  131. lines=5,
  132. label="Output",
  133. )
  134. ],
  135. title="🦙🌲 Alpaca-LoRA",
  136. 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
  137. ).launch(server_name=server_name, share=share_gradio)
  138. # Old testing code follows.
  139. """
  140. # testing code for readme
  141. for instruction in [
  142. "Tell me about alpacas.",
  143. "Tell me about the president of Mexico in 2019.",
  144. "Tell me about the king of France in 2019.",
  145. "List all Canadian provinces in alphabetical order.",
  146. "Write a Python program that prints the first 10 Fibonacci numbers.",
  147. "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
  148. "Tell me five words that rhyme with 'shock'.",
  149. "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
  150. "Count up from 1 to 500.",
  151. ]:
  152. print("Instruction:", instruction)
  153. print("Response:", evaluate(instruction))
  154. print()
  155. """
  156. if __name__ == "__main__":
  157. fire.Fire(main)