chat_completion.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 torch
  6. import os
  7. import sys
  8. import warnings
  9. from typing import List
  10. from peft import PeftModel, PeftConfig
  11. from transformers import LlamaConfig, LlamaTokenizer, LlamaForCausalLM
  12. from safety_utils import get_safety_checker
  13. from model_utils import load_model, load_peft_model
  14. from chat_utils import read_dialogs_from_file, format_tokens
  15. def main(
  16. model_name,
  17. peft_model: str=None,
  18. quantization: bool=False,
  19. max_new_tokens =256, #The maximum numbers of tokens to generate
  20. min_new_tokens:int=0, #The minimum numbers of tokens to generate
  21. prompt_file: str=None,
  22. seed: int=42, #seed value for reproducibility
  23. safety_score_threshold: float=0.5,
  24. do_sample: bool=True, #Whether or not to use sampling ; use greedy decoding otherwise.
  25. 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.
  26. 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.
  27. temperature: float=1.0, # [optional] The value used to modulate the next token probabilities.
  28. top_k: int=50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
  29. repetition_penalty: float=1.0, #The parameter for repetition penalty. 1.0 means no penalty.
  30. length_penalty: int=1, #[optional] Exponential penalty to the length that is used with beam-based generation.
  31. enable_azure_content_safety: bool=False, # Enable safety check with Azure content safety api
  32. enable_sensitive_topics: bool=False, # Enable check for sensitive topics using AuditNLG APIs
  33. enable_saleforce_content_safety: bool=True, # Enable safety check woth Saleforce safety flan t5
  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. torch.cuda.manual_seed(seed)
  50. torch.manual_seed(seed)
  51. model = load_model(model_name, quantization)
  52. if peft_model:
  53. model = load_peft_model(model, peft_model)
  54. tokenizer = LlamaTokenizer.from_pretrained(model_name)
  55. tokenizer.add_special_tokens(
  56. {
  57. "pad_token": "<PAD>",
  58. }
  59. )
  60. chats = format_tokens(dialogs, tokenizer)
  61. with torch.no_grad():
  62. for idx, chat in enumerate(chats):
  63. safety_checker = get_safety_checker(enable_azure_content_safety,
  64. enable_sensitive_topics,
  65. enable_saleforce_content_safety,
  66. )
  67. # Safety check of the user prompt
  68. safety_results = [check(dialogs[idx][0]["content"]) for check in safety_checker]
  69. are_safe = all([r[1] for r in safety_results])
  70. if are_safe:
  71. print(f"User prompt deemed safe.")
  72. print("User prompt:\n", dialogs[idx][0]["content"])
  73. print("\n==================================\n")
  74. else:
  75. print("User prompt deemed unsafe.")
  76. for method, is_safe, report in safety_results:
  77. if not is_safe:
  78. print(method)
  79. print(report)
  80. print("Skipping the inferece as the prompt is not safe.")
  81. sys.exit(1) # Exit the program with an error status
  82. tokens= torch.tensor(chat).long()
  83. tokens= tokens.unsqueeze(0)
  84. tokens= tokens.to("cuda:0")
  85. outputs = model.generate(
  86. tokens,
  87. max_new_tokens=max_new_tokens,
  88. do_sample=do_sample,
  89. top_p=top_p,
  90. temperature=temperature,
  91. use_cache=use_cache,
  92. top_k=top_k,
  93. repetition_penalty=repetition_penalty,
  94. length_penalty=length_penalty,
  95. **kwargs
  96. )
  97. output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
  98. # Safety check of the model output
  99. safety_results = [check(output_text) for check in safety_checker]
  100. are_safe = all([r[1] for r in safety_results])
  101. if are_safe:
  102. print("User input and model output deemed safe.")
  103. print(f"Model output:\n{output_text}")
  104. print("\n==================================\n")
  105. else:
  106. print("Model output deemed unsafe.")
  107. for method, is_safe, report in safety_results:
  108. if not is_safe:
  109. print(method)
  110. print(report)
  111. if __name__ == "__main__":
  112. fire.Fire(main)