inference.py 6.5 KB

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