code_instruct_example.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 fire
  4. import os
  5. import sys
  6. import time
  7. import torch
  8. from transformers import AutoTokenizer
  9. from llama_recipes.inference.safety_utils import get_safety_checker
  10. from llama_recipes.inference.model_utils import load_model, load_peft_model
  11. def handle_safety_check(are_safe_user_prompt, user_prompt, safety_results_user_prompt, are_safe_system_prompt, system_prompt, safety_results_system_prompt):
  12. """
  13. Handles the output based on the safety check of both user and system prompts.
  14. Parameters:
  15. - are_safe_user_prompt (bool): Indicates whether the user prompt is safe.
  16. - user_prompt (str): The user prompt that was checked for safety.
  17. - safety_results_user_prompt (list of tuples): A list of tuples for the user prompt containing the method, safety status, and safety report.
  18. - are_safe_system_prompt (bool): Indicates whether the system prompt is safe.
  19. - system_prompt (str): The system prompt that was checked for safety.
  20. - safety_results_system_prompt (list of tuples): A list of tuples for the system prompt containing the method, safety status, and safety report.
  21. """
  22. def print_safety_results(are_safe_prompt, prompt, safety_results, prompt_type="User"):
  23. """
  24. Prints the safety results for a prompt.
  25. Parameters:
  26. - are_safe_prompt (bool): Indicates whether the prompt is safe.
  27. - prompt (str): The prompt that was checked for safety.
  28. - safety_results (list of tuples): A list of tuples containing the method, safety status, and safety report.
  29. - prompt_type (str): The type of prompt (User/System).
  30. """
  31. if are_safe_prompt:
  32. print(f"{prompt_type} prompt deemed safe.")
  33. print(f"{prompt_type} prompt:\n{prompt}")
  34. else:
  35. print(f"{prompt_type} prompt deemed unsafe.")
  36. for method, is_safe, report in safety_results:
  37. if not is_safe:
  38. print(method)
  39. print(report)
  40. print(f"Skipping the inference as the {prompt_type.lower()} prompt is not safe.")
  41. sys.exit(1)
  42. # Check user prompt
  43. print_safety_results(are_safe_user_prompt, user_prompt, safety_results_user_prompt, "User")
  44. # Check system prompt
  45. print_safety_results(are_safe_system_prompt, system_prompt, safety_results_system_prompt, "System")
  46. def main(
  47. model_name,
  48. peft_model: str=None,
  49. quantization: bool=False,
  50. max_new_tokens =100, #The maximum numbers of tokens to generate
  51. seed: int=42, #seed value for reproducibility
  52. do_sample: bool=True, #Whether or not to use sampling ; use greedy decoding otherwise.
  53. min_length: int=None, #The minimum length of the sequence to be generated, input prompt + min_new_tokens
  54. use_cache: bool=False, #[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.
  55. top_p: float=0.9, # [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.
  56. temperature: float=0.6, # [optional] The value used to modulate the next token probabilities.
  57. top_k: int=50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
  58. repetition_penalty: float=1.0, #The parameter for repetition penalty. 1.0 means no penalty.
  59. length_penalty: int=1, #[optional] Exponential penalty to the length that is used with beam-based generation.
  60. enable_azure_content_safety: bool=False, # Enable safety check with Azure content safety api
  61. enable_sensitive_topics: bool=False, # Enable check for sensitive topics using AuditNLG APIs
  62. enable_salesforce_content_safety: bool=True, # Enable safety check with Salesforce safety flan t5
  63. enable_llamaguard_content_safety: bool=False, # Enable safety check with Llama-Guard
  64. use_fast_kernels: bool = True, # Enable using SDPA from PyTroch Accelerated Transformers, make use Flash Attention and Xformer memory-efficient kernels
  65. **kwargs
  66. ):
  67. system_prompt = input("Please insert your system prompt: ")
  68. user_prompt = input("Please insert your prompt: ")
  69. chat = [
  70. {"role": "system", "content": system_prompt},
  71. {"role": "user", "content": user_prompt},
  72. ]
  73. # Set the seeds for reproducibility
  74. torch.cuda.manual_seed(seed)
  75. torch.manual_seed(seed)
  76. model = load_model(model_name, quantization, use_fast_kernels)
  77. if peft_model:
  78. model = load_peft_model(model, peft_model)
  79. model.eval()
  80. tokenizer = AutoTokenizer.from_pretrained(model_name)
  81. safety_checker = get_safety_checker(enable_azure_content_safety,
  82. enable_sensitive_topics,
  83. enable_salesforce_content_safety,
  84. enable_llamaguard_content_safety,
  85. )
  86. # Safety check of the user prompt
  87. safety_results_user_prompt = [check(user_prompt) for check in safety_checker]
  88. safety_results_system_prompt = [check(system_prompt) for check in safety_checker]
  89. are_safe_user_prompt = all([r[1] for r in safety_results_user_prompt])
  90. are_safe_system_prompt = all([r[1] for r in safety_results_system_prompt])
  91. handle_safety_check(are_safe_user_prompt, user_prompt, safety_results_user_prompt, are_safe_system_prompt, system_prompt, safety_results_system_prompt)
  92. inputs = tokenizer.apply_chat_template(chat, return_tensors="pt").to("cuda")
  93. start = time.perf_counter()
  94. with torch.no_grad():
  95. outputs = model.generate(
  96. input_ids=inputs,
  97. max_new_tokens=max_new_tokens,
  98. do_sample=do_sample,
  99. top_p=top_p,
  100. temperature=temperature,
  101. min_length=min_length,
  102. use_cache=use_cache,
  103. top_k=top_k,
  104. repetition_penalty=repetition_penalty,
  105. length_penalty=length_penalty,
  106. **kwargs
  107. )
  108. e2e_inference_time = (time.perf_counter()-start)*1000
  109. print(f"the inference time is {e2e_inference_time} ms")
  110. output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
  111. # Safety check of the model output
  112. safety_results = [check(output_text) for check in safety_checker]
  113. are_safe = all([r[1] for r in safety_results])
  114. if are_safe:
  115. print("User input and model output deemed safe.")
  116. print(f"Model output:\n{output_text}")
  117. else:
  118. print("Model output deemed unsafe.")
  119. for method, is_safe, report in safety_results:
  120. if not is_safe:
  121. print(method)
  122. print(report)
  123. if __name__ == "__main__":
  124. fire.Fire(main)