chat_completion.py 6.1 KB

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