inference.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. from typing import List
  9. from transformers import LlamaTokenizer
  10. from safety_utils import get_safety_checker
  11. from model_utils import load_model, load_peft_model, load_llama_from_config
  12. # Get the current file's directory
  13. current_directory = os.path.dirname(os.path.abspath(__file__))
  14. # Get the parent directory
  15. parent_directory = os.path.dirname(current_directory)
  16. # Append the parent directory to sys.path
  17. sys.path.append(parent_directory)
  18. from model_checkpointing import load_sharded_model_single_gpu
  19. def main(
  20. model_name,
  21. peft_model: str=None,
  22. quantization: bool=False,
  23. max_new_tokens =100, #The maximum numbers of tokens to generate
  24. prompt_file: str=None,
  25. seed: int=42, #seed value for reproducibility
  26. do_sample: bool=True, #Whether or not to use sampling ; use greedy decoding otherwise.
  27. min_length: int=None, #The minimum length of the sequence to be generated, input prompt + min_new_tokens
  28. 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.
  29. 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.
  30. temperature: float=1.0, # [optional] The value used to modulate the next token probabilities.
  31. top_k: int=50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
  32. repetition_penalty: float=1.0, #The parameter for repetition penalty. 1.0 means no penalty.
  33. length_penalty: int=1, #[optional] Exponential penalty to the length that is used with beam-based generation.
  34. enable_azure_content_safety: bool=False, # Enable safety check with Azure content safety api
  35. enable_sensitive_topics: bool=False, # Enable check for sensitive topics using AuditNLG APIs
  36. enable_saleforce_content_safety: bool=True, # Enable safety check woth Saleforce safety flan t5
  37. **kwargs
  38. ):
  39. if prompt_file is not None:
  40. assert os.path.exists(
  41. prompt_file
  42. ), f"Provided Prompt file does not exist {prompt_file}"
  43. with open(prompt_file, "r") as f:
  44. user_prompt = "\n".join(f.readlines())
  45. elif not sys.stdin.isatty():
  46. user_prompt = "\n".join(sys.stdin.readlines())
  47. else:
  48. print("No user prompt provided. Exiting.")
  49. sys.exit(1)
  50. # Set the seeds for reproducibility
  51. torch.cuda.manual_seed(seed)
  52. torch.manual_seed(seed)
  53. # model = load_model(model_name, quantization)
  54. model = load_llama_from_config()
  55. loaded_model = load_sharded_model_single_gpu(model, model_name)
  56. print("model has been loaded *******************")
  57. tokenizer = LlamaTokenizer.from_pretrained(model_name)
  58. tokenizer.add_special_tokens(
  59. {
  60. "eos_token": "</s>",
  61. "bos_token": "</s>",
  62. "unk_token": "</s>",
  63. "pad_token": "[PAD]",
  64. }
  65. )
  66. safety_checker = get_safety_checker(enable_azure_content_safety,
  67. enable_sensitive_topics,
  68. enable_saleforce_content_safety,
  69. )
  70. # Safety check of the user prompt
  71. safety_results = [check(user_prompt) for check in safety_checker]
  72. are_safe = all([r[1] for r in safety_results])
  73. if are_safe:
  74. print("User prompt deemed safe.")
  75. print(f"User prompt:\n{user_prompt}")
  76. else:
  77. print("User prompt deemed unsafe.")
  78. for method, is_safe, report in safety_results:
  79. if not is_safe:
  80. print(method)
  81. print(report)
  82. print("Skipping the inferece as the prompt is not safe.")
  83. sys.exit(1) # Exit the program with an error status
  84. if peft_model:
  85. model = load_peft_model(model, peft_model)
  86. model.eval()
  87. batch = tokenizer(user_prompt, return_tensors="pt")
  88. batch = {k: v.to("cuda") for k, v in batch.items()}
  89. with torch.no_grad():
  90. outputs = model.generate(
  91. **batch,
  92. max_new_tokens=max_new_tokens,
  93. do_sample=do_sample,
  94. top_p=top_p,
  95. temperature=temperature,
  96. min_length=min_length,
  97. use_cache=use_cache,
  98. top_k=top_k,
  99. repetition_penalty=repetition_penalty,
  100. length_penalty=length_penalty,
  101. **kwargs
  102. )
  103. output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
  104. # Safety check of the model output
  105. safety_results = [check(output_text) for check in safety_checker]
  106. are_safe = all([r[1] for r in safety_results])
  107. if are_safe:
  108. print("User input and model output deemed safe.")
  109. print(f"Model output:\n{output_text}")
  110. else:
  111. print("Model output deemed unsafe.")
  112. for method, is_safe, report in safety_results:
  113. if not is_safe:
  114. print(method)
  115. print(report)
  116. if __name__ == "__main__":
  117. fire.Fire(main)