inference.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import os
  4. import sys
  5. import time
  6. import fire
  7. import torch
  8. from accelerate.utils import is_xpu_available
  9. from llama_recipes.inference.model_utils import load_model, load_peft_model
  10. from llama_recipes.inference.safety_utils import AgentType, get_safety_checker
  11. from transformers import AutoTokenizer
  12. def main(
  13. model_name,
  14. peft_model: str = None,
  15. quantization: str = None, # Options: 4bit, 8bit
  16. max_new_tokens=100, # The maximum numbers of tokens to generate
  17. prompt_file: str = None,
  18. seed: int = 42, # seed value for reproducibility
  19. do_sample: bool = True, # Whether or not to use sampling ; use greedy decoding otherwise.
  20. min_length: int = None, # The minimum length of the sequence to be generated, input prompt + min_new_tokens
  21. use_cache: bool = True, # [optional] Whether or not the model should use the past last key/values attentions Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
  22. top_p: float = 1.0, # [optional] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
  23. temperature: float = 1.0, # [optional] The value used to modulate the next token probabilities.
  24. top_k: int = 50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
  25. repetition_penalty: float = 1.0, # The parameter for repetition penalty. 1.0 means no penalty.
  26. length_penalty: int = 1, # [optional] Exponential penalty to the length that is used with beam-based generation.
  27. enable_azure_content_safety: bool = False, # Enable safety check with Azure content safety api
  28. enable_sensitive_topics: bool = False, # Enable check for sensitive topics using AuditNLG APIs
  29. enable_salesforce_content_safety: bool = True, # Enable safety check with Salesforce safety flan t5
  30. enable_llamaguard_content_safety: bool = False,
  31. max_padding_length: int = None, # the max padding length to be used with tokenizer padding the prompts.
  32. use_fast_kernels: bool = False, # Enable using SDPA from PyTroch Accelerated Transformers, make use Flash Attention and Xformer memory-efficient kernels
  33. share_gradio: bool = False, # Enable endpoint creation for gradio.live
  34. **kwargs,
  35. ):
  36. # Set the seeds for reproducibility
  37. if is_xpu_available():
  38. torch.xpu.manual_seed(seed)
  39. else:
  40. torch.cuda.manual_seed(seed)
  41. torch.manual_seed(seed)
  42. model = load_model(model_name, quantization, use_fast_kernels, **kwargs)
  43. if peft_model:
  44. model = load_peft_model(model, peft_model)
  45. model.eval()
  46. tokenizer = AutoTokenizer.from_pretrained(model_name)
  47. tokenizer.pad_token = tokenizer.eos_token
  48. def inference(
  49. user_prompt,
  50. temperature,
  51. top_p,
  52. top_k,
  53. max_new_tokens,
  54. **kwargs,
  55. ):
  56. safety_checker = get_safety_checker(
  57. enable_azure_content_safety,
  58. enable_sensitive_topics,
  59. enable_salesforce_content_safety,
  60. enable_llamaguard_content_safety,
  61. )
  62. # Safety check of the user prompt
  63. safety_results = [check(user_prompt) for check in safety_checker]
  64. are_safe = all([r[1] for r in safety_results])
  65. if are_safe:
  66. print("User prompt deemed safe.")
  67. print(f"User prompt:\n{user_prompt}")
  68. else:
  69. print("User prompt deemed unsafe.")
  70. for method, is_safe, report in safety_results:
  71. if not is_safe:
  72. print(method)
  73. print(report)
  74. print("Skipping the inference as the prompt is not safe.")
  75. return # Exit the program with an error status
  76. batch = tokenizer(
  77. user_prompt,
  78. truncation=True,
  79. max_length=max_padding_length,
  80. return_tensors="pt",
  81. )
  82. if is_xpu_available():
  83. batch = {k: v.to("xpu") for k, v in batch.items()}
  84. else:
  85. batch = {k: v.to("cuda") for k, v in batch.items()}
  86. start = time.perf_counter()
  87. with torch.no_grad():
  88. outputs = model.generate(
  89. **batch,
  90. max_new_tokens=max_new_tokens,
  91. do_sample=do_sample,
  92. top_p=top_p,
  93. temperature=temperature,
  94. min_length=min_length,
  95. use_cache=use_cache,
  96. top_k=top_k,
  97. repetition_penalty=repetition_penalty,
  98. length_penalty=length_penalty,
  99. **kwargs,
  100. )
  101. e2e_inference_time = (time.perf_counter() - start) * 1000
  102. print(f"the inference time is {e2e_inference_time} ms")
  103. output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
  104. # Safety check of the model output
  105. safety_results = [
  106. check(output_text, agent_type=AgentType.AGENT, user_prompt=user_prompt)
  107. for check in safety_checker
  108. ]
  109. are_safe = all([r[1] for r in safety_results])
  110. if are_safe:
  111. print("User input and model output deemed safe.")
  112. print(f"Model output:\n{output_text}")
  113. return output_text
  114. else:
  115. print("Model output deemed unsafe.")
  116. for method, is_safe, report in safety_results:
  117. if not is_safe:
  118. print(method)
  119. print(report)
  120. return None
  121. if prompt_file is not None:
  122. assert os.path.exists(
  123. prompt_file
  124. ), f"Provided Prompt file does not exist {prompt_file}"
  125. with open(prompt_file, "r") as f:
  126. user_prompt = "\n".join(f.readlines())
  127. inference(user_prompt, temperature, top_p, top_k, max_new_tokens)
  128. elif not sys.stdin.isatty():
  129. user_prompt = "\n".join(sys.stdin.readlines())
  130. inference(user_prompt, temperature, top_p, top_k, max_new_tokens)
  131. else:
  132. try:
  133. import gradio as gr
  134. except ImportError:
  135. raise ImportError("This part of the recipe requires gradio. Please run `pip install gradio`")
  136. gr.Interface(
  137. fn=inference,
  138. inputs=[
  139. gr.components.Textbox(
  140. lines=9,
  141. label="User Prompt",
  142. placeholder="none",
  143. ),
  144. gr.components.Slider(
  145. minimum=0, maximum=1, value=1.0, label="Temperature"
  146. ),
  147. gr.components.Slider(minimum=0, maximum=1, value=1.0, label="Top p"),
  148. gr.components.Slider(
  149. minimum=0, maximum=100, step=1, value=50, label="Top k"
  150. ),
  151. gr.components.Slider(
  152. minimum=1, maximum=2000, step=1, value=200, label="Max tokens"
  153. ),
  154. ],
  155. outputs=[
  156. gr.components.Textbox(
  157. lines=5,
  158. label="Output",
  159. )
  160. ],
  161. title="Meta Llama3 Playground",
  162. description="https://github.com/meta-llama/llama-recipes",
  163. ).queue().launch(server_name="0.0.0.0", share=share_gradio)
  164. if __name__ == "__main__":
  165. fire.Fire(main)