chat_completion.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. # from accelerate import init_empty_weights, load_checkpoint_and_dispatch
  4. import fire
  5. import os
  6. import sys
  7. import torch
  8. from transformers import LlamaTokenizer
  9. from llama_recipes.inference.chat_utils import read_dialogs_from_file, format_tokens
  10. from llama_recipes.inference.model_utils import load_model, load_peft_model
  11. from llama_recipes.inference.safety_utils import get_safety_checker
  12. from accelerate.utils import is_xpu_available
  13. def main(
  14. model_name,
  15. peft_model: str=None,
  16. quantization: bool=False,
  17. max_new_tokens =256, #The maximum numbers of tokens to generate
  18. min_new_tokens:int=0, #The minimum numbers of tokens to generate
  19. prompt_file: str=None,
  20. seed: int=42, #seed value for reproducibility
  21. safety_score_threshold: float=0.5,
  22. do_sample: bool=True, #Whether or not to use sampling ; use greedy decoding otherwise.
  23. 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.
  24. 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.
  25. temperature: float=1.0, # [optional] The value used to modulate the next token probabilities.
  26. top_k: int=50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
  27. repetition_penalty: float=1.0, #The parameter for repetition penalty. 1.0 means no penalty.
  28. length_penalty: int=1, #[optional] Exponential penalty to the length that is used with beam-based generation.
  29. enable_azure_content_safety: bool=False, # Enable safety check with Azure content safety api
  30. enable_sensitive_topics: bool=False, # Enable check for sensitive topics using AuditNLG APIs
  31. enable_saleforce_content_safety: bool=True, # Enable safety check woth Saleforce safety flan t5
  32. use_fast_kernels: bool = False, # Enable using SDPA from PyTorch Accelerated Transformers, make use Flash Attention and Xformer memory-efficient kernels
  33. enable_llamaguard_content_safety: bool = False,
  34. **kwargs
  35. ):
  36. if prompt_file is not None:
  37. assert os.path.exists(
  38. prompt_file
  39. ), f"Provided Prompt file does not exist {prompt_file}"
  40. dialogs= read_dialogs_from_file(prompt_file)
  41. elif not sys.stdin.isatty():
  42. dialogs = "\n".join(sys.stdin.readlines())
  43. else:
  44. print("No user prompt provided. Exiting.")
  45. sys.exit(1)
  46. print(f"User dialogs:\n{dialogs}")
  47. print("\n==================================\n")
  48. # Set the seeds for reproducibility
  49. if is_xpu_available():
  50. torch.xpu.manual_seed(seed)
  51. else:
  52. torch.cuda.manual_seed(seed)
  53. torch.manual_seed(seed)
  54. model = load_model(model_name, quantization)
  55. if peft_model:
  56. model = load_peft_model(model, peft_model)
  57. if use_fast_kernels:
  58. """
  59. Setting 'use_fast_kernels' will enable
  60. using of Flash Attention or Xformer memory-efficient kernels
  61. based on the hardware being used. This would speed up inference when used for batched inputs.
  62. """
  63. try:
  64. from optimum.bettertransformer import BetterTransformer
  65. model = BetterTransformer.transform(model)
  66. except ImportError:
  67. print("Module 'optimum' not found. Please install 'optimum' it before proceeding.")
  68. tokenizer = LlamaTokenizer.from_pretrained(model_name)
  69. tokenizer.add_special_tokens(
  70. {
  71. "pad_token": "<PAD>",
  72. }
  73. )
  74. chats = format_tokens(dialogs, tokenizer)
  75. with torch.no_grad():
  76. for idx, chat in enumerate(chats):
  77. safety_checker = get_safety_checker(enable_azure_content_safety,
  78. enable_sensitive_topics,
  79. enable_saleforce_content_safety,
  80. enable_llamaguard_content_safety,
  81. )
  82. # Safety check of the user prompt
  83. safety_results = [check(dialogs[idx][0]["content"]) for check in safety_checker]
  84. are_safe = all([r[1] for r in safety_results])
  85. if are_safe:
  86. print(f"User prompt deemed safe.")
  87. print("User prompt:\n", dialogs[idx][0]["content"])
  88. print("\n==================================\n")
  89. else:
  90. print("User prompt deemed unsafe.")
  91. for method, is_safe, report in safety_results:
  92. if not is_safe:
  93. print(method)
  94. print(report)
  95. print("Skipping the inferece as the prompt is not safe.")
  96. sys.exit(1) # Exit the program with an error status
  97. tokens= torch.tensor(chat).long()
  98. tokens= tokens.unsqueeze(0)
  99. if is_xpu_available():
  100. tokens= tokens.to("xpu:0")
  101. else:
  102. tokens= tokens.to("cuda:0")
  103. outputs = model.generate(
  104. input_ids=tokens,
  105. max_new_tokens=max_new_tokens,
  106. do_sample=do_sample,
  107. top_p=top_p,
  108. temperature=temperature,
  109. use_cache=use_cache,
  110. top_k=top_k,
  111. repetition_penalty=repetition_penalty,
  112. length_penalty=length_penalty,
  113. **kwargs
  114. )
  115. output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
  116. # Safety check of the model output
  117. safety_results = [check(output_text) for check in safety_checker]
  118. are_safe = all([r[1] for r in safety_results])
  119. if are_safe:
  120. print("User input and model output deemed safe.")
  121. print(f"Model output:\n{output_text}")
  122. print("\n==================================\n")
  123. else:
  124. print("Model output deemed unsafe.")
  125. for method, is_safe, report in safety_results:
  126. if not is_safe:
  127. print(method)
  128. print(report)
  129. if __name__ == "__main__":
  130. fire.Fire(main)