inference.py 5.3 KB

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